'use client';

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

export default function OrgTenantDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const { orgAdmin, loading } = useOrgAdmin();
  const router = useRouter();
  const [tenant, setTenant] = useState<any>(null);
  const [showAdminForm, setShowAdminForm] = useState(false);
  const [adminForm, setAdminForm] = useState({ email: '', password: '', role: 'ADMIN' });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (loading) return;
    if (!orgAdmin) { router.replace('/org/login'); return; }
    fetch(`/api/org/tenants/${id}`)
      .then((r) => r.ok ? r.json() : null)
      .then((d) => setTenant(d))
      .catch(() => {});
  }, [orgAdmin, loading, router, id]);

  async function handleCreateAdmin(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    setSaving(true);
    try {
      const res = await fetch(`/api/org/tenants/${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(Array.isArray(err.message) ? err.message.join(', ') : (err.message ?? 'Failed'));
      }
      setShowAdminForm(false);
      setAdminForm({ email: '', password: '', role: 'ADMIN' });
      const updated = await fetch(`/api/org/tenants/${id}`).then((r) => r.ok ? r.json() : null);
      if (updated) setTenant(updated);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error');
    } finally {
      setSaving(false);
    }
  }

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

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

      <div className="grid grid-cols-3 gap-4 mb-8">
        {[
          { label: 'Messages', value: tenant._count?.messages },
          { label: 'Members', value: tenant._count?.towerUsers },
          { label: 'Groups', value: tenant._count?.groups },
        ].map((stat) => (
          <div key={stat.label} className="bg-white rounded-xl border p-5">
            <p className="text-2xl font-bold">{stat.value ?? '—'}</p>
            <p className="text-sm text-gray-500">{stat.label}</p>
          </div>
        ))}
      </div>

      <div className="bg-white rounded-xl border overflow-hidden">
        <div className="px-5 py-4 border-b flex items-center justify-between">
          <h2 className="font-semibold">Chapter 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-3 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">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="OWNER">OWNER</option>
                  <option value="ADMIN">ADMIN</option>
                  <option value="VIEWER">VIEWER</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); setError(''); }} 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">Role</th>
              <th className="px-4 py-3 font-medium">Joined</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {(tenant.admins ?? []).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">
                  <span className="text-xs font-medium px-2 py-1 rounded-full bg-gray-100 text-gray-700">{a.role}</span>
                </td>
                <td className="px-4 py-3 text-gray-500">{new Date(a.createdAt).toLocaleDateString()}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {tenant.admins?.length === 0 && <p className="p-4 text-gray-400">No admins yet.</p>}
      </div>
    </div>
  );
}
