'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);

  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]);

  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">
          <h2 className="font-semibold">Chapter Admins</h2>
        </div>
        <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>
  );
}
