'use client';

import { useEffect, useState } from 'react';
import { useSuperAdmin } from '../../_lib/super-admin-context';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function AdminOrgsPage() {
  const { admin, loading } = useSuperAdmin();
  const router = useRouter();
  const [orgs, setOrgs] = useState<any[]>([]);
  const [showAdd, setShowAdd] = useState(false);
  const [form, setForm] = useState({ slug: '', name: '' });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  async function load() {
    const res = await fetch('/api/admin/orgs');
    if (res.ok) setOrgs(await res.json());
  }

  useEffect(() => {
    if (loading) return;
    if (!admin) { router.replace('/admin/login'); return; }
    void load();
  }, [admin, loading, router]);

  async function handleAdd(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    setSaving(true);
    try {
      const res = await fetch('/api/admin/orgs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.message ?? 'Failed');
      }
      setShowAdd(false);
      setForm({ slug: '', name: '' });
      void load();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error');
    } finally {
      setSaving(false);
    }
  }

  if (loading) return <p className="text-gray-500">Loading...</p>;
  if (!admin) return null;

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">Organizations</h1>
        <button
          onClick={() => setShowAdd(!showAdd)}
          className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700"
        >
          Create Org
        </button>
      </div>

      {showAdd && (
        <form onSubmit={(e) => void handleAdd(e)} className="bg-white rounded-xl border p-5 mb-6 flex flex-col gap-4">
          <h2 className="font-semibold">New Organization</h2>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1">Name</label>
              <input
                type="text"
                value={form.name}
                onChange={(e) => setForm({ ...form, name: e.target.value })}
                className="w-full border rounded-lg px-3 py-2 text-sm"
                placeholder="UP Parivaar"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Slug</label>
              <input
                type="text"
                value={form.slug}
                onChange={(e) => setForm({ ...form, slug: e.target.value })}
                className="w-full border rounded-lg px-3 py-2 text-sm"
                placeholder="org_up_parivaar"
                required
              />
            </div>
          </div>
          {error && <p className="text-red-600 text-sm">{error}</p>}
          <div className="flex gap-2">
            <button type="submit" disabled={saving} className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700 disabled:opacity-50">
              {saving ? 'Creating...' : 'Create'}
            </button>
            <button type="button" onClick={() => setShowAdd(false)} className="border rounded-lg px-4 py-2 text-sm hover:bg-gray-50">
              Cancel
            </button>
          </div>
        </form>
      )}

      <div className="bg-white rounded-xl border overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-left">
            <tr>
              <th className="px-4 py-3 font-medium">Name</th>
              <th className="px-4 py-3 font-medium">Slug</th>
              <th className="px-4 py-3 font-medium">Chapters</th>
              <th className="px-4 py-3 font-medium">Org Admins</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {orgs.map((org: any) => (
              <tr key={org.id} className="hover:bg-gray-50">
                <td className="px-4 py-3">
                  <Link href={`/admin/orgs/${org.id}`} className="text-blue-600 hover:underline font-medium">
                    {org.name}
                  </Link>
                </td>
                <td className="px-4 py-3 text-gray-500">{org.slug}</td>
                <td className="px-4 py-3">{org._count?.tenants ?? 0}</td>
                <td className="px-4 py-3">{org._count?.orgAdmins ?? 0}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {orgs.length === 0 && <p className="p-4 text-gray-400">No organizations yet.</p>}
      </div>
    </div>
  );
}
