'use client';

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

export default function OrgDashboardPage() {
  const { orgAdmin, loading } = useOrgAdmin();
  const router = useRouter();
  const [data, setData] = useState<any>(null);

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

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

  return (
    <div>
      <h1 className="text-2xl font-bold mb-1">{orgAdmin.organization?.name ?? 'Organization'}</h1>
      <p className="text-sm text-gray-500 mb-6">{data?.chapterCount ?? '—'} chapters</p>

      <div className="grid gap-4">
        {(data?.chapters ?? []).map((chapter: any) => (
          <div key={chapter.id} className="bg-white rounded-xl border p-5 flex items-center justify-between">
            <div>
              <Link href={`/org/tenants/${chapter.id}`} className="font-medium text-blue-600 hover:underline">
                {chapter.name}
              </Link>
              <p className="text-xs text-gray-500 mt-1">{chapter.slug}</p>
            </div>
            <div className="flex gap-6 text-sm text-right">
              <div>
                <p className="font-medium">{chapter.messageCount}</p>
                <p className="text-xs text-gray-400">messages</p>
              </div>
              <div>
                <p className="font-medium">{chapter.memberCount}</p>
                <p className="text-xs text-gray-400">members</p>
              </div>
              <div>
                <p className="font-medium">{chapter.adminCount}</p>
                <p className="text-xs text-gray-400">admins</p>
              </div>
              <span className={`self-center text-xs font-medium px-2 py-1 rounded-full ${chapter.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                {chapter.isActive ? 'Active' : 'Inactive'}
              </span>
            </div>
          </div>
        ))}
        {data && data.chapters.length === 0 && (
          <p className="text-gray-400">No chapters yet. <Link href="/org/tenants" className="text-blue-600 hover:underline">Add a chapter</Link>.</p>
        )}
      </div>
    </div>
  );
}
