'use client';

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

export default function AdminOrgDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const { admin, loading } = useSuperAdmin();
  const router = useRouter();
  const [org, setOrg] = useState<any>(null);
  const [showAdminForm, setShowAdminForm] = useState(false);
  const [adminForm, setAdminForm] = useState({ email: '', password: '', name: '', role: 'ORG_OWNER' });
  const [tenantId, setTenantId] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  async function load() {
    const res = await fetch(`/api/admin/orgs/${id}`);
    if (res.ok) setOrg(await res.json());
  }

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

  async function handleCreateAdmin(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    setSaving(true);
    try {
      const res = await fetch(`/api/admin/orgs/${id}/admins`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(adminForm),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.message ?? 'Failed');
      }
      setShowAdminForm(false);
      setAdminForm({ email: '', password: '', name: '', role: 'ORG_OWNER' });
      void load();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error');
    } finally {
      setSaving(false);
    }
  }

  async function handleAssignTenant(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const res = await fetch(`/api/admin/tenants/${tenantId}/org`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ organizationId: id }),
      });
      if (!res.ok) throw new Error('Failed to assign');
      setTenantId('');
      void load();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error');
    } finally {
      setSaving(false);
    }
  }

  if (loading || !admin) return <p className="text-gray-500">Loading...</p>;
  if (!org) return <p className="text-gray-400">Organization not found.</p>;

  return (
    <div>
      <button onClick={() => router.back()} className="text-sm text-gray-500 hover:text-gray-700 mb-3">← Back</button>
      <h1 className="text-2xl font-bold mb-1">{org.name}</h1>
      <p className="text-sm text-gray-500 mb-6">{org.slug}</p>

      {/* Chapters */}
      <div className="bg-white rounded-xl border mb-6">
        <div className="px-5 py-4 border-b flex items-center justify-between">
          <h2 className="font-semibold">Chapters</h2>
          <form onSubmit={(e) => void handleAssignTenant(e)} className="flex gap-2">
            <input
              type="text"
              value={tenantId}
              onChange={(e) => setTenantId(e.target.value)}
              className="border rounded-lg px-3 py-1.5 text-sm"
              placeholder="Tenant ID to assign"
            />
            <button type="submit" disabled={!tenantId || saving} className="bg-blue-600 text-white rounded-lg px-3 py-1.5 text-sm font-medium hover:bg-blue-700 disabled:opacity-50">
              Assign
            </button>
          </form>
        </div>
        <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">Status</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {(org.tenants ?? []).map((t: any) => (
              <tr key={t.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 font-medium">{t.name}</td>
                <td className="px-4 py-3 text-gray-500">{t.slug}</td>
                <td className="px-4 py-3">
                  <span className={`text-xs font-medium px-2 py-1 rounded-full ${t.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                    {t.isActive ? 'Active' : 'Inactive'}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {org.tenants?.length === 0 && <p className="p-4 text-gray-400">No chapters assigned.</p>}
      </div>

      {/* Org Admins */}
      <div className="bg-white rounded-xl border">
        <div className="px-5 py-4 border-b flex items-center justify-between">
          <h2 className="font-semibold">Org Admins</h2>
          <button
            onClick={() => setShowAdminForm(!showAdminForm)}
            className="bg-blue-600 text-white rounded-lg px-3 py-1.5 text-sm font-medium hover:bg-blue-700"
          >
            Add Admin
          </button>
        </div>

        {showAdminForm && (
          <form onSubmit={(e) => void handleCreateAdmin(e)} className="p-5 border-b flex flex-col gap-3">
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium mb-1">Email</label>
                <input type="email" value={adminForm.email} onChange={(e) => setAdminForm({ ...adminForm, email: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" required />
              </div>
              <div>
                <label className="block text-xs font-medium mb-1">Password</label>
                <input type="password" value={adminForm.password} onChange={(e) => setAdminForm({ ...adminForm, password: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" required />
              </div>
              <div>
                <label className="block text-xs font-medium mb-1">Name</label>
                <input type="text" value={adminForm.name} onChange={(e) => setAdminForm({ ...adminForm, name: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" />
              </div>
              <div>
                <label className="block text-xs font-medium mb-1">Role</label>
                <select value={adminForm.role} onChange={(e) => setAdminForm({ ...adminForm, role: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm">
                  <option value="ORG_OWNER">ORG_OWNER</option>
                  <option value="ORG_ADMIN">ORG_ADMIN</option>
                </select>
              </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 ? 'Saving...' : 'Create'}</button>
              <button type="button" onClick={() => setShowAdminForm(false)} className="border rounded-lg px-4 py-2 text-sm hover:bg-gray-50">Cancel</button>
            </div>
          </form>
        )}

        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-left">
            <tr>
              <th className="px-4 py-3 font-medium">Email</th>
              <th className="px-4 py-3 font-medium">Name</th>
              <th className="px-4 py-3 font-medium">Role</th>
              <th className="px-4 py-3 font-medium">Created</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {(org.orgAdmins ?? []).map((a: any) => (
              <tr key={a.id} className="hover:bg-gray-50">
                <td className="px-4 py-3">{a.email}</td>
                <td className="px-4 py-3 text-gray-500">{a.name ?? '—'}</td>
                <td className="px-4 py-3">
                  <span className="text-xs font-medium px-2 py-1 rounded-full bg-purple-100 text-purple-700">{a.role}</span>
                </td>
                <td className="px-4 py-3 text-gray-500">{new Date(a.createdAt).toLocaleDateString()}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {org.orgAdmins?.length === 0 && <p className="p-4 text-gray-400">No org admins yet.</p>}
      </div>
    </div>
  );
}
