"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { Search, ChevronRight } from "lucide-react";

interface Org { id: string; name: string; createdAt: string; _count: { brands: number; memberships: number } }

export default function AdminOrganizations() {
  const [orgs, setOrgs] = useState<Org[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [query, setQuery] = useState("");
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch(`/api/admin/organizations?page=${page}${query ? `&q=${encodeURIComponent(query)}` : ""}`);
    if (res.ok) { const d = await res.json(); setOrgs(d.organizations ?? []); setTotal(d.total ?? 0); }
    setLoading(false);
  }, [page, query]);
  useEffect(() => { load(); }, [load]);

  const pages = Math.ceil(total / 50);

  return (
    <div className="space-y-6 max-w-6xl">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-slate-900">Organizations</h1>
        <span className="text-sm text-slate-500">{total} total</span>
      </div>

      <div className="relative"><Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" /><input value={query} onChange={(e) => { setQuery(e.target.value); setPage(1); }} placeholder="Search organizations..." className="w-full pl-10 pr-4 py-2.5 text-sm border border-slate-200 rounded-lg bg-white" /></div>

      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <table className="w-full text-sm">
          <thead><tr className="border-b border-slate-100 bg-slate-50/80 text-[10px] font-bold uppercase tracking-widest text-slate-400">
            <th className="px-4 py-2.5 text-left">Organization</th><th className="px-4 py-2.5 text-center">Brands</th><th className="px-4 py-2.5 text-center">Users</th><th className="px-4 py-2.5 text-left">Created</th><th className="w-10" />
          </tr></thead>
          <tbody>
            {loading ? <tr><td colSpan={5} className="px-4 py-12 text-center text-slate-400">Loading...</td></tr> :
            orgs.map((org) => (
              <tr key={org.id} className="border-b border-slate-50 hover:bg-slate-50">
                <td className="px-4 py-2.5 font-semibold text-slate-900">{org.name}</td>
                <td className="px-4 py-2.5 text-center tabular-nums">{org._count.brands}</td>
                <td className="px-4 py-2.5 text-center tabular-nums">{org._count.memberships}</td>
                <td className="px-4 py-2.5 text-slate-500">{new Date(org.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</td>
                <td className="px-4 py-2.5"><Link href={`/admin/organizations/${org.id}`} className="text-brand-600 hover:text-brand-800"><ChevronRight className="w-4 h-4" /></Link></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {pages > 1 && <div className="flex items-center justify-center gap-2"><button disabled={page <= 1} onClick={() => setPage(page - 1)} className="px-3 py-1 rounded-md text-xs font-semibold border border-slate-200 disabled:opacity-40">Prev</button><span className="text-xs text-slate-500">Page {page} of {pages}</span><button disabled={page >= pages} onClick={() => setPage(page + 1)} className="px-3 py-1 rounded-md text-xs font-semibold border border-slate-200 disabled:opacity-40">Next</button></div>}
    </div>
  );
}
