'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { useSuperAdmin } from '../../_lib/super-admin-context';
import { useRouter } from 'next/navigation';

export default function BotsPage() {
  const { admin, loading } = useSuperAdmin();
  const router = useRouter();
  const [bots, setBots] = useState<any[]>([]);
  const [tenants, setTenants] = useState<any[]>([]);
  const [initiating, setInitiating] = useState(false);
  const [pairingInfo, setPairingInfo] = useState<{ pairingToken: string; expiresAt: string } | null>(null);
  const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
  const [qrStatus, setQrStatus] = useState<string>('PAIRING');
  const [assigningBotId, setAssigningBotId] = useState<string | null>(null);
  const [assignTenantId, setAssignTenantId] = useState('');
  const [assignBusy, setAssignBusy] = useState(false);
  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);

  async function load() {
    const [botsRes, tenantsRes] = await Promise.all([
      fetch('/api/admin/bots'),
      fetch('/api/admin/tenants'),
    ]);
    if (botsRes.ok) setBots(await botsRes.json());
    if (tenantsRes.ok) setTenants(await tenantsRes.json());
  }

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

  const pollQr = useCallback(async (token: string) => {
    const res = await fetch(`/api/admin/bots/qr/${token}`);
    if (!res.ok) { clearInterval(pollRef.current!); return; }
    const data = await res.json();
    setQrStatus(data.status);
    if (data.qrDataUrl) {
      setQrDataUrl(data.qrDataUrl);
      clearInterval(pollRef.current!);
    }
    if (data.status === 'ACTIVE') {
      clearInterval(pollRef.current!);
      setPairingInfo(null);
      void load();
    }
  }, []);

  useEffect(() => {
    return () => { if (pollRef.current) clearInterval(pollRef.current); };
  }, []);

  async function initiateBot() {
    setInitiating(true);
    setQrDataUrl(null);
    setQrStatus('PAIRING');
    try {
      const res = await fetch('/api/admin/bots', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({}),
      });
      if (res.ok) {
        const data = await res.json();
        setPairingInfo(data);
        pollRef.current = setInterval(() => void pollQr(data.pairingToken), 2000);
        void pollQr(data.pairingToken);
      }
    } finally {
      setInitiating(false);
      void load();
    }
  }

  async function removeBot(id: string) {
    if (!confirm('Remove this bot? Only possible if no tenants are assigned.')) return;
    const res = await fetch(`/api/admin/bots/${id}`, { method: 'DELETE' });
    if (res.ok) {
      void load();
    } else {
      const err = await res.json();
      alert(err.message ?? 'Failed to remove bot');
    }
  }

  async function assignBot() {
    if (!assigningBotId || !assignTenantId) return;
    setAssignBusy(true);
    try {
      const res = await fetch(`/api/admin/bots/${assigningBotId}/assign`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ tenantId: assignTenantId }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        alert(err.message ?? 'Failed to assign bot');
        return;
      }
      setAssigningBotId(null);
      setAssignTenantId('');
      void load();
    } finally {
      setAssignBusy(false);
    }
  }

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

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">Bot Pool</h1>
        <button
          onClick={initiateBot}
          disabled={initiating}
          className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm disabled:opacity-50"
        >
          {initiating ? 'Creating...' : 'Add Bot'}
        </button>
      </div>

      {pairingInfo && (
        <div className="bg-yellow-50 border border-yellow-200 rounded-xl p-4 mb-6 flex items-start gap-6">
          <div className="flex-1">
            <p className="text-sm font-medium mb-1">
              {qrStatus === 'ACTIVE' ? 'Bot connected!' : 'New bot created — waiting for QR scan...'}
            </p>
            <p className="text-xs text-gray-600">Status: {qrStatus}</p>
            <p className="text-xs text-gray-600">Expires: {pairingInfo.expiresAt}</p>
          </div>
          {qrDataUrl ? (
            <img src={qrDataUrl} alt="QR Code" className="w-40 h-40 border-2 border-gray-300 rounded-lg" />
          ) : (
            <div className="w-40 h-40 bg-gray-100 border-2 border-dashed border-gray-300 rounded-lg flex items-center justify-center text-xs text-gray-400">
              {qrStatus === 'ACTIVE' ? 'Connected' : 'Waiting for QR...'}
            </div>
          )}
        </div>
      )}

      <div className="bg-white rounded-xl border overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-left">
            <tr>
              <th className="px-4 py-3 font-medium">JID</th>
              <th className="px-4 py-3 font-medium">Name</th>
              <th className="px-4 py-3 font-medium">Status</th>
              <th className="px-4 py-3 font-medium">Chapters</th>
              <th className="px-4 py-3 font-medium">Created</th>
              <th className="px-4 py-3 font-medium"></th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {bots.map((b: any) => (
              <>
                <tr key={b.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3 font-mono text-xs">{b.jid?.slice(0, 30) ?? 'pending...'}</td>
                  <td className="px-4 py-3">{b.displayName ?? '—'}</td>
                  <td className="px-4 py-3">
                    <span className={`text-xs font-medium px-2 py-1 rounded-full ${
                      b.status === 'ACTIVE' ? 'bg-green-100 text-green-700' :
                      b.status === 'PAIRING' ? 'bg-yellow-100 text-yellow-700' :
                      'bg-gray-100 text-gray-500'
                    }`}>{b.status}</span>
                  </td>
                  <td className="px-4 py-3">{b.tenantCount}</td>
                  <td className="px-4 py-3 text-xs text-gray-500">{new Date(b.createdAt).toLocaleDateString()}</td>
                  <td className="px-4 py-3 flex gap-3">
                    <button
                      onClick={() => { setAssigningBotId(assigningBotId === b.id ? null : b.id); setAssignTenantId(''); }}
                      className="text-blue-600 text-xs hover:underline"
                    >
                      Assign
                    </button>
                    <button
                      onClick={() => removeBot(b.id)}
                      className="text-red-600 text-xs hover:underline"
                    >
                      Remove
                    </button>
                  </td>
                </tr>
                {assigningBotId === b.id && (
                  <tr key={`${b.id}-assign`} className="bg-blue-50">
                    <td colSpan={6} className="px-4 py-3">
                      <div className="flex items-center gap-3">
                        <span className="text-xs font-medium text-gray-600">Assign to chapter:</span>
                        <select
                          value={assignTenantId}
                          onChange={(e) => setAssignTenantId(e.target.value)}
                          className="border rounded-lg px-3 py-1.5 text-sm flex-1 max-w-xs bg-white"
                        >
                          <option value="">— select chapter —</option>
                          {tenants.map((t: any) => (
                            <option key={t.id} value={t.id}>{t.name} ({t.slug})</option>
                          ))}
                        </select>
                        <button
                          onClick={() => void assignBot()}
                          disabled={!assignTenantId || assignBusy}
                          className="bg-blue-600 text-white rounded-lg px-3 py-1.5 text-xs font-medium hover:bg-blue-700 disabled:opacity-50"
                        >
                          {assignBusy ? 'Assigning...' : 'Confirm'}
                        </button>
                        <button
                          onClick={() => { setAssigningBotId(null); setAssignTenantId(''); }}
                          className="text-xs text-gray-500 hover:text-gray-700"
                        >
                          Cancel
                        </button>
                      </div>
                    </td>
                  </tr>
                )}
              </>
            ))}
          </tbody>
        </table>
        {bots.length === 0 && <p className="p-4 text-gray-400">No bots in the pool.</p>}
      </div>
    </div>
  );
}
