'use client';

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

export default function TenantDetailPage() {
  const { admin, loading } = useSuperAdmin();
  const router = useRouter();
  const params = useParams();
  const [tenant, setTenant] = useState<any>(null);
  const [busy, setBusy] = useState(false);

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

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

  async function toggleActive() {
    setBusy(true);
    await fetch(`/api/admin/tenants/${params.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ isActive: !tenant.isActive }),
    });
    await load();
    setBusy(false);
  }

  async function togglePaused() {
    setBusy(true);
    await fetch(`/api/admin/tenants/${params.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ isForwardingPaused: !tenant.isForwardingPaused }),
    });
    await load();
    setBusy(false);
  }

  if (loading) return <p className="text-gray-500">Loading...</p>;
  if (!admin) return null;
  if (!tenant) return <p className="text-gray-500">Loading tenant...</p>;

  return (
    <div className="max-w-2xl">
      <h1 className="text-2xl font-bold mb-2">{tenant.name}</h1>
      <p className="text-gray-500 text-sm mb-6">Slug: {tenant.slug}</p>

      <div className="grid grid-cols-2 gap-4 mb-8">
        <div className="bg-white rounded-xl border p-4">
          <div className="text-xs text-gray-500 uppercase">Status</div>
          <button
            onClick={toggleActive}
            disabled={busy}
            className={`mt-1 text-sm font-medium px-3 py-1 rounded-full ${tenant.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}
          >
            {tenant.isActive ? 'Active' : 'Inactive'}
          </button>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="text-xs text-gray-500 uppercase">Forwarding</div>
          <button
            onClick={togglePaused}
            disabled={busy}
            className={`mt-1 text-sm font-medium px-3 py-1 rounded-full ${tenant.isForwardingPaused ? 'bg-yellow-100 text-yellow-700' : 'bg-green-100 text-green-700'}`}
          >
            {tenant.isForwardingPaused ? 'Paused' : 'Active'}
          </button>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="text-xs text-gray-500 uppercase">Groups</div>
          <div className="text-xl font-bold mt-1">{tenant.stats?.groups ?? 0}</div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="text-xs text-gray-500 uppercase">Messages</div>
          <div className="text-xl font-bold mt-1">{tenant.stats?.messages ?? 0}</div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="text-xs text-gray-500 uppercase">Rules</div>
          <div className="text-xl font-bold mt-1">{tenant.stats?.rules ?? 0}</div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="text-xs text-gray-500 uppercase">Routes</div>
          <div className="text-xl font-bold mt-1">{tenant.stats?.routes ?? 0}</div>
        </div>
      </div>

      {tenant.bot && (
        <div className="bg-white rounded-xl border p-4 mb-6">
          <h2 className="font-semibold text-sm mb-2">Assigned Bot</h2>
          <div className="text-xs space-y-1">
            <p><span className="text-gray-500">JID:</span> <span className="font-mono">{tenant.bot.jid}</span></p>
            <p><span className="text-gray-500">Name:</span> {tenant.bot.displayName ?? '—'}</p>
            <p><span className="text-gray-500">Status:</span> {tenant.bot.status}</p>
            <p><span className="text-gray-500">Linked:</span> {tenant.bot.linkedSince}</p>
          </div>
        </div>
      )}

      {tenant.admins && tenant.admins.length > 0 && (
        <div className="bg-white rounded-xl border p-4">
          <h2 className="font-semibold text-sm mb-2">Admins</h2>
          <div className="text-xs space-y-1">
            {tenant.admins.map((a: any) => (
              <p key={a.id}>{a.email} — <span className="uppercase">{a.role}</span></p>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
