import { useState, useEffect } from 'react';
import api from '../services/api';
import {
  MessageSquare, RefreshCw, CheckCircle2, XCircle,
  Clock, AlertTriangle, Inbox, ArrowDownLeft, ArrowUpRight,
} from 'lucide-react';

// ── Tipos ─────────────────────────────────────────────────────────────────────

type Tab = 'logs' | 'errors' | 'inbox';

const OUTGOING_TYPES = [
  { value: '', label: 'Todos' },
  { value: 'purchase_confirmed',       label: 'Compra' },
  { value: 'purchase_pending',         label: 'Pendente' },
  { value: 'winner',                   label: 'Ganhador' },
  { value: 'welcome',                  label: 'Boas-vindas' },
  { value: 'security_login',           label: 'Segurança' },
  { value: 'price_drop',               label: 'Preço' },
  { value: 'last_hours',               label: 'Últ. Horas' },
  { value: 'reservation_expiring',     label: 'Reserva' },
  { value: 'club_welcome',             label: 'Clube: Boas-vindas' },
  { value: 'club_payment_confirmed',   label: 'Clube: Pagamento' },
  { value: 'club_payment_overdue',     label: 'Clube: Atraso' },
  { value: 'club_payment_reminder',    label: 'Clube: Lembrete' },
  { value: 'club_suspended',           label: 'Clube: Suspenso' },
  { value: 'club_canceled',            label: 'Clube: Cancelado' },
];

function fmtDate(s: string) {
  return new Date(s).toLocaleString('pt-BR', {
    day: '2-digit', month: '2-digit', year: '2-digit',
    hour: '2-digit', minute: '2-digit',
  });
}

function statusIcon(status: string) {
  if (status === 'sent')    return <CheckCircle2 size={15} className="text-emerald-400" />;
  if (status === 'failed')  return <XCircle      size={15} className="text-rose-400" />;
  return                           <Clock        size={15} className="text-slate-500" />;
}

function statusColor(s: string) {
  if (s === 'sent')    return 'text-emerald-400';
  if (s === 'failed')  return 'text-rose-400';
  return 'text-slate-500';
}

// ── Aba: Logs de saída ────────────────────────────────────────────────────────

function OutgoingLogs() {
  const [logs, setLogs]           = useState<any[]>([]);
  const [loading, setLoading]     = useState(true);
  const [typeFilter, setTypeFilter] = useState('');

  const fetch = async () => {
    setLoading(true);
    try { const r = await api.get('/analytics/whatsapp-logs'); setLogs(r.data); }
    catch {}
    finally { setLoading(false); }
  };
  useEffect(() => { fetch(); }, []);

  const counts = logs.reduce((a: Record<string,number>, l) => {
    a[l.status] = (a[l.status] || 0) + 1; return a;
  }, {});
  const filtered = typeFilter ? logs.filter(l => l.type === typeFilter) : logs;

  return (
    <div className="space-y-6">
      {/* Contadores */}
      <div className="flex gap-3 flex-wrap">
        {[
          { key: 'sent',      label: 'Enviados',  color: 'emerald' },
          { key: 'retrying',  label: 'Tentando',  color: 'amber' },
          { key: 'failed',    label: 'Falhas',    color: 'rose' },
          { key: 'processing',label: 'Processando', color: 'cyan' },
        ].map(s => (
          <div key={s.key} className="bg-slate-900/40 border border-slate-800 rounded-2xl px-5 py-3 flex items-center gap-3">
            <span className={`text-2xl font-black tabular-nums text-${s.color}-400`}>{counts[s.key] ?? 0}</span>
            <span className="text-slate-500 text-xs font-bold uppercase tracking-widest">{s.label}</span>
          </div>
        ))}
      </div>

      {/* Filtros por tipo */}
      <div className="flex gap-1.5 flex-wrap">
        {OUTGOING_TYPES.map(tab => {
          const cnt = tab.value ? logs.filter(l => l.type === tab.value).length : logs.length;
          return (
            <button key={tab.value} onClick={() => setTypeFilter(tab.value)}
              className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all border ${
                typeFilter === tab.value
                  ? 'text-cyan-400 bg-cyan-400/10 border-cyan-500/30'
                  : 'text-slate-500 bg-slate-900 border-slate-800 hover:border-slate-700 hover:text-slate-300'
              }`}>
              {tab.label}
              {cnt > 0 && (
                <span className="ml-1.5 text-[9px] bg-slate-700 text-slate-400 px-1.5 py-0.5 rounded-full">{cnt}</span>
              )}
            </button>
          );
        })}
      </div>

      <Table loading={loading} empty={filtered.length === 0}
        head={['Status','Telefone','Tipo','Payload','Data']}
        emptyMsg="Nenhuma notificação registrada.">
        {filtered.map(log => (
          <tr key={log.id} className="hover:bg-slate-800/20 transition-colors">
            <td className="px-6 py-4">
              <div className="flex items-center gap-2">
                {statusIcon(log.status)}
                <span className={`text-[10px] font-black uppercase tracking-widest ${statusColor(log.status)}`}>
                  {log.status}
                </span>
              </div>
            </td>
            <td className="px-6 py-4 text-sm text-slate-300 font-mono">{log.phone ?? '—'}</td>
            <td className="px-6 py-4">
              <span className="bg-slate-800 text-slate-400 px-2 py-1 rounded text-[10px] font-bold uppercase tracking-tight">
                {log.type?.replace(/_/g,' ')}
              </span>
            </td>
            <td className="px-6 py-4 text-xs text-slate-500 font-mono max-w-xs truncate">
              {JSON.stringify(log.payload)}
            </td>
            <td className="px-6 py-4 text-[11px] text-slate-500 whitespace-nowrap">{fmtDate(log.created_at)}</td>
          </tr>
        ))}
      </Table>
    </div>
  );
}

// ── Aba: Falhas Definitivas ───────────────────────────────────────────────────

function FailedErrors() {
  const [data, setData]       = useState<{ rows: any[]; total: number }>({ rows: [], total: 0 });
  const [loading, setLoading] = useState(true);
  const [phone, setPhone]     = useState('');

  const fetch = async () => {
    setLoading(true);
    try {
      const r = await api.get('/admin/notification-errors', { params: { phone: phone || undefined, limit: 100 } });
      setData(r.data);
    } catch {}
    finally { setLoading(false); }
  };
  useEffect(() => { fetch(); }, []);

  return (
    <div className="space-y-6">
      <div className="flex gap-3 items-center">
        <div className="bg-rose-500/10 border border-rose-500/20 rounded-2xl px-5 py-3 flex items-center gap-3">
          <span className="text-2xl font-black text-rose-400">{data.total}</span>
          <span className="text-slate-500 text-xs font-bold uppercase tracking-widest">falhas definitivas</span>
        </div>
        <input value={phone} onChange={e => setPhone(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && fetch()}
          placeholder="Filtrar por telefone…"
          className="bg-slate-900 border border-slate-700 rounded-xl px-4 py-2.5 text-sm text-slate-300 focus:outline-none focus:border-slate-500 w-56" />
      </div>

      <Table loading={loading} empty={data.rows.length === 0}
        head={['Telefone','Erro','Payload','Job ID','Data']}
        emptyMsg="Nenhuma falha definitiva registrada. ✅">
        {data.rows.map(row => (
          <tr key={row.id} className="hover:bg-slate-800/20 transition-colors">
            <td className="px-6 py-4 text-sm text-rose-300 font-mono">{row.phone ?? '—'}</td>
            <td className="px-6 py-4 text-xs text-slate-400 max-w-xs">{row.error_message}</td>
            <td className="px-6 py-4 text-xs text-slate-500 font-mono max-w-xs truncate">
              {JSON.stringify(row.payload)}
            </td>
            <td className="px-6 py-4 text-[10px] text-slate-600 font-mono">{row.job_id}</td>
            <td className="px-6 py-4 text-[11px] text-slate-500 whitespace-nowrap">{fmtDate(row.created_at)}</td>
          </tr>
        ))}
      </Table>
    </div>
  );
}

// ── Aba: Inbox Recebidos ──────────────────────────────────────────────────────

function InboxEvents() {
  const [data, setData]           = useState<{ rows: any[]; total: number }>({ rows: [], total: 0 });
  const [loading, setLoading]     = useState(true);
  const [eventFilter, setEventFilter] = useState('');
  const [dirFilter, setDirFilter] = useState('');

  const fetch = async () => {
    setLoading(true);
    try {
      const r = await api.get('/admin/nw-events', {
        params: { event: eventFilter || undefined, direction: dirFilter || undefined, limit: 100 },
      });
      setData(r.data);
    } catch {}
    finally { setLoading(false); }
  };
  useEffect(() => { fetch(); }, []);

  const dirIcon = (d: string) =>
    d === 'in'
      ? <ArrowDownLeft size={13} className="text-emerald-400" />
      : <ArrowUpRight  size={13} className="text-cyan-400" />;

  return (
    <div className="space-y-6">
      <div className="flex gap-2 flex-wrap items-center">
        <div className="bg-slate-900/40 border border-slate-800 rounded-2xl px-5 py-3 flex items-center gap-3">
          <span className="text-2xl font-black text-slate-300">{data.total}</span>
          <span className="text-slate-500 text-xs font-bold uppercase tracking-widest">eventos</span>
        </div>

        {/* Event filter */}
        {['','message.new','session.status'].map(e => (
          <button key={e} onClick={() => { setEventFilter(e); }}
            className={`px-3 py-1.5 rounded-xl text-xs font-bold border transition-all ${
              eventFilter === e
                ? 'text-cyan-400 bg-cyan-400/10 border-cyan-500/30'
                : 'text-slate-500 bg-slate-900 border-slate-800 hover:text-slate-300'
            }`}>
            {e || 'Todos'}
          </button>
        ))}

        {/* Direction filter */}
        {['','in','out'].map(d => (
          <button key={d} onClick={() => setDirFilter(d)}
            className={`px-3 py-1.5 rounded-xl text-xs font-bold border transition-all ${
              dirFilter === d
                ? 'text-violet-400 bg-violet-400/10 border-violet-500/30'
                : 'text-slate-500 bg-slate-900 border-slate-800 hover:text-slate-300'
            }`}>
            {d === '' ? 'Todos' : d === 'in' ? '↙ Recebidos' : '↗ Enviados'}
          </button>
        ))}

        <button onClick={fetch} className="p-2 bg-slate-800 rounded-xl border border-slate-700 hover:bg-slate-700 transition-all">
          <RefreshCw size={14} className="text-slate-400" />
        </button>
      </div>

      <Table loading={loading} empty={data.rows.length === 0}
        head={['Direção','Evento','Instância','Chat ID','Tipo msg','Payload','Data']}
        emptyMsg="Nenhum evento recebido ainda.">
        {data.rows.map(row => (
          <tr key={row.id} className="hover:bg-slate-800/20 transition-colors">
            <td className="px-6 py-4">
              <div className="flex items-center gap-1.5">
                {dirIcon(row.direction)}
                <span className={`text-[10px] font-black uppercase ${row.direction === 'in' ? 'text-emerald-400' : 'text-cyan-400'}`}>
                  {row.direction}
                </span>
              </div>
            </td>
            <td className="px-6 py-4">
              <span className="bg-slate-800 text-slate-400 px-2 py-1 rounded text-[10px] font-bold">
                {row.event}
              </span>
            </td>
            <td className="px-6 py-4 text-xs text-slate-400 font-mono">{row.instance_id || '—'}</td>
            <td className="px-6 py-4 text-xs text-slate-500 font-mono max-w-[120px] truncate">{row.chat_id || '—'}</td>
            <td className="px-6 py-4 text-[10px] text-slate-600 uppercase">{row.msg_type || '—'}</td>
            <td className="px-6 py-4 text-xs text-slate-500 font-mono max-w-xs truncate">
              {JSON.stringify(row.payload)}
            </td>
            <td className="px-6 py-4 text-[11px] text-slate-500 whitespace-nowrap">{fmtDate(row.created_at)}</td>
          </tr>
        ))}
      </Table>
    </div>
  );
}

// ── Shared Table shell ────────────────────────────────────────────────────────

function Table({ loading, empty, head, emptyMsg, children }: {
  loading: boolean; empty: boolean; head: string[]; emptyMsg: string; children: React.ReactNode;
}) {
  return (
    <div className="bg-slate-900/50 border border-slate-800 rounded-3xl overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full text-left">
          <thead>
            <tr className="bg-slate-800/30 text-slate-500 text-[10px] uppercase tracking-widest font-bold">
              {head.map(h => <th key={h} className="px-6 py-4">{h}</th>)}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-800">
            {loading
              ? [1,2,3].map(i => (
                  <tr key={i} className="animate-pulse">
                    <td colSpan={head.length} className="px-6 py-6 bg-slate-800/10" />
                  </tr>
                ))
              : empty
              ? (
                <tr>
                  <td colSpan={head.length} className="px-6 py-20 text-center text-slate-500">
                    <div className="flex flex-col items-center gap-3">
                      <MessageSquare size={36} className="text-slate-800" />
                      <p className="text-sm">{emptyMsg}</p>
                    </div>
                  </td>
                </tr>
              )
              : children}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Página principal ──────────────────────────────────────────────────────────

const TABS: { key: Tab; label: string; icon: React.ReactNode }[] = [
  { key: 'logs',   label: 'Logs de Saída',        icon: <MessageSquare  size={14} /> },
  { key: 'errors', label: 'Falhas Definitivas',    icon: <AlertTriangle  size={14} /> },
  { key: 'inbox',  label: 'Inbox Recebidos',       icon: <Inbox          size={14} /> },
];

export default function WhatsAppLogsPage() {
  const [tab, setTab] = useState<Tab>('logs');
  const [, forceRefresh] = useState(0);

  return (
    <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <header className="flex justify-between items-center">
        <div>
          <h2 className="text-3xl font-black text-white tracking-tighter uppercase italic">Auditoria WhatsApp</h2>
          <p className="text-slate-400 mt-1">Logs de envio, falhas definitivas e mensagens recebidas.</p>
        </div>
        <button onClick={() => forceRefresh(n => n + 1)}
          className="p-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl transition-all border border-slate-700">
          <RefreshCw size={18} />
        </button>
      </header>

      {/* Tab bar */}
      <div className="flex gap-1 bg-slate-900/60 border border-slate-800 rounded-2xl p-1 w-fit">
        {TABS.map(t => (
          <button key={t.key} onClick={() => setTab(t.key)}
            className={`flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition-all ${
              tab === t.key
                ? 'bg-slate-700 text-white'
                : 'text-slate-500 hover:text-slate-300'
            }`}>
            {t.icon}{t.label}
          </button>
        ))}
      </div>

      {tab === 'logs'   && <OutgoingLogs   key="logs"   />}
      {tab === 'errors' && <FailedErrors   key="errors" />}
      {tab === 'inbox'  && <InboxEvents    key="inbox"  />}
    </div>
  );
}
