/**
 * WhatsAppWebhooks — gestão de webhooks da integração NewWhats.
 *
 * Permite registrar URLs externas que recebem push de eventos WhatsApp
 * (message.new, session.status) assinados com HMAC-SHA256.
 */
import { useState, useEffect, useCallback } from 'react';
import {
  Webhook, Plus, Trash2, Power, PowerOff,
  Copy, Check, RefreshCw, AlertCircle, Shield,
  ChevronDown, ChevronUp,
} from 'lucide-react';
import { NwService, type NwWebhook } from '../services/api';

const AVAILABLE_EVENTS = [
  { id: 'message.new',    label: 'Nova mensagem',      desc: 'Disparado a cada mensagem recebida ou enviada' },
  { id: 'session.status', label: 'Status da sessão',   desc: 'Disparado quando uma instância conecta ou desconecta' },
];

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' });
}

// ─── CopyButton ───────────────────────────────────────────────────────────────
function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);
  const copy = () => {
    navigator.clipboard.writeText(text).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); });
  };
  return (
    <button onClick={copy} className="p-1 rounded hover:bg-black/5 transition-colors text-[#8696a0] hover:text-[#54656f]" title="Copiar">
      {copied ? <Check size={13} className="text-[#00a884]" /> : <Copy size={13} />}
    </button>
  );
}

// ─── EventBadge ───────────────────────────────────────────────────────────────
function EventBadge({ event }: { event: string }) {
  const colors: Record<string, string> = {
    'message.new':    'bg-[#00a884]/10 text-[#00a884] border-[#00a884]/20',
    'session.status': 'bg-blue-500/10 text-blue-600 border-blue-500/20',
  };
  const labels: Record<string, string> = {
    'message.new':    'message.new',
    'session.status': 'session.status',
  };
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-semibold border ${colors[event] ?? 'bg-gray-100 text-gray-600 border-gray-200'}`}>
      {labels[event] ?? event}
    </span>
  );
}

// ─── WebhookCard ─────────────────────────────────────────────────────────────
function WebhookCard({
  hook, onDelete, onToggle,
}: { hook: NwWebhook; onDelete: (id: string) => void; onToggle: (id: string, active: boolean) => void }) {
  const [expanded, setExpanded] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [toggling, setToggling] = useState(false);
  const [confirmDel, setConfirmDel] = useState(false);

  const handleDelete = async () => {
    if (!confirmDel) { setConfirmDel(true); setTimeout(() => setConfirmDel(false), 3000); return; }
    setDeleting(true);
    try { await NwService.deleteWebhook(hook.id); onDelete(hook.id); }
    catch { /* silencioso */ }
    finally { setDeleting(false); }
  };

  const handleToggle = async () => {
    setToggling(true);
    try { await NwService.toggleWebhook(hook.id, !hook.active); onToggle(hook.id, !hook.active); }
    catch { /* silencioso */ }
    finally { setToggling(false); }
  };

  return (
    <div className={`bg-white rounded-xl border transition-all ${hook.active ? 'border-[#d1d7db]' : 'border-[#d1d7db] opacity-60'}`}>
      {/* Header row */}
      <div className="flex items-center gap-3 px-4 py-3">
        {/* Status dot */}
        <div className={`w-2.5 h-2.5 rounded-full flex-shrink-0 ${hook.active ? 'bg-[#00a884] animate-pulse' : 'bg-[#8696a0]'}`} />

        {/* URL + copy */}
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-1">
            <span className="text-[14px] font-mono text-[#111b21] truncate">{hook.url}</span>
            <CopyButton text={hook.url} />
          </div>
          <div className="flex items-center gap-1.5 mt-1 flex-wrap">
            {hook.events.map(e => <EventBadge key={e} event={e} />)}
            <span className="text-[11px] text-[#8696a0] ml-1">{fmtDate(hook.createdAt)}</span>
          </div>
        </div>

        {/* Actions */}
        <div className="flex items-center gap-1 flex-shrink-0">
          <button
            onClick={handleToggle}
            disabled={toggling}
            title={hook.active ? 'Desativar' : 'Ativar'}
            className="p-2 rounded-full hover:bg-black/5 transition-colors disabled:opacity-40"
          >
            {hook.active
              ? <Power size={16} className="text-[#00a884]" />
              : <PowerOff size={16} className="text-[#8696a0]" />
            }
          </button>
          <button
            onClick={handleDelete}
            disabled={deleting}
            title={confirmDel ? 'Clique novamente para confirmar' : 'Remover'}
            className={`p-2 rounded-full transition-colors disabled:opacity-40 ${confirmDel ? 'bg-red-50 text-red-500' : 'hover:bg-black/5 text-[#8696a0] hover:text-red-500'}`}
          >
            <Trash2 size={16} />
          </button>
          <button onClick={() => setExpanded(v => !v)} className="p-2 rounded-full hover:bg-black/5 transition-colors text-[#8696a0]">
            {expanded ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
          </button>
        </div>
      </div>

      {/* Expanded: info de integração */}
      {expanded && (
        <div className="border-t border-[#f0f2f5] px-4 py-3 bg-[#f9fafb] rounded-b-xl space-y-3">
          <div>
            <p className="text-[11px] font-semibold text-[#667781] uppercase tracking-wide mb-1">Como validar a assinatura</p>
            <pre className="text-[12px] bg-white border border-[#d1d7db] rounded-lg p-3 overflow-x-auto text-[#111b21] leading-relaxed whitespace-pre-wrap">
{`// Node.js
const crypto = require('crypto');
const sig = req.headers['x-nw-signature'];
const expected = 'sha256=' + crypto
  .createHmac('sha256', '<seu-secret>')
  .update(JSON.stringify(req.body))
  .digest('hex');
if (sig !== expected) return res.status(401).end();`}
            </pre>
          </div>
          <div>
            <p className="text-[11px] font-semibold text-[#667781] uppercase tracking-wide mb-1">ID do webhook</p>
            <div className="flex items-center gap-1">
              <code className="text-[12px] text-[#54656f] font-mono">{hook.id}</code>
              <CopyButton text={hook.id} />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── CreateForm ───────────────────────────────────────────────────────────────
function CreateForm({ onCreated }: { onCreated: (hook: NwWebhook) => void }) {
  const [url,     setUrl]     = useState('');
  const [secret,  setSecret]  = useState('');
  const [events,  setEvents]  = useState<string[]>(['message.new']);
  const [saving,  setSaving]  = useState(false);
  const [error,   setError]   = useState<string | null>(null);

  const toggleEvent = (id: string) =>
    setEvents(prev => prev.includes(id) ? prev.filter(e => e !== id) : [...prev, id]);

  const generateSecret = () => {
    const arr = new Uint8Array(24);
    crypto.getRandomValues(arr);
    setSecret(Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join(''));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSaving(true);
    try {
      const hook = await NwService.createWebhook({ url, events, secret });
      onCreated(hook);
      setUrl(''); setSecret(''); setEvents(['message.new']);
    } catch (err: any) {
      setError(err.response?.data?.error ?? 'Erro ao criar webhook');
    } finally {
      setSaving(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="bg-white rounded-xl border border-[#d1d7db] p-5 space-y-4">
      <h3 className="text-[15px] font-semibold text-[#111b21] flex items-center gap-2">
        <Plus size={16} className="text-[#00a884]" /> Novo webhook
      </h3>

      {/* URL */}
      <div>
        <label className="block text-[12px] font-semibold text-[#667781] uppercase tracking-wide mb-1">URL de destino</label>
        <input
          type="url"
          value={url}
          onChange={e => setUrl(e.target.value)}
          placeholder="https://meu-sistema.com/webhook/whatsapp"
          required
          className="w-full bg-[#f0f2f5] rounded-lg px-3 py-2 text-[14px] text-[#111b21] placeholder:text-[#8696a0] outline-none focus:ring-2 focus:ring-[#00a884]/30 border border-transparent focus:border-[#00a884]/30"
        />
      </div>

      {/* Eventos */}
      <div>
        <label className="block text-[12px] font-semibold text-[#667781] uppercase tracking-wide mb-2">Eventos</label>
        <div className="flex flex-wrap gap-2">
          {AVAILABLE_EVENTS.map(ev => (
            <button
              key={ev.id}
              type="button"
              onClick={() => toggleEvent(ev.id)}
              className={`flex flex-col items-start px-3 py-2 rounded-lg border text-left transition-all ${
                events.includes(ev.id)
                  ? 'bg-[#00a884]/5 border-[#00a884]/40 text-[#00a884]'
                  : 'bg-[#f0f2f5] border-transparent text-[#54656f] hover:border-[#d1d7db]'
              }`}
            >
              <span className="text-[13px] font-semibold font-mono">{ev.id}</span>
              <span className="text-[11px] opacity-80 mt-0.5">{ev.desc}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Secret */}
      <div>
        <label className="block text-[12px] font-semibold text-[#667781] uppercase tracking-wide mb-1">
          Secret <span className="font-normal normal-case">(mínimo 16 caracteres)</span>
        </label>
        <div className="flex gap-2">
          <input
            type="text"
            value={secret}
            onChange={e => setSecret(e.target.value)}
            placeholder="sua-chave-secreta-hmac"
            required
            minLength={16}
            className="flex-1 bg-[#f0f2f5] rounded-lg px-3 py-2 text-[14px] font-mono text-[#111b21] placeholder:text-[#8696a0] outline-none focus:ring-2 focus:ring-[#00a884]/30 border border-transparent focus:border-[#00a884]/30"
          />
          <button
            type="button"
            onClick={generateSecret}
            className="px-3 py-2 bg-[#f0f2f5] rounded-lg text-[13px] text-[#54656f] hover:bg-[#e9edef] transition-colors flex items-center gap-1.5 font-medium flex-shrink-0"
          >
            <Shield size={13} /> Gerar
          </button>
        </div>
        <p className="text-[11px] text-[#8696a0] mt-1 flex items-center gap-1">
          <Shield size={10} /> Guarde este secret — ele não será exibido novamente após a criação.
        </p>
      </div>

      {error && (
        <div className="flex items-center gap-2 text-red-600 text-[13px] bg-red-50 px-3 py-2 rounded-lg border border-red-100">
          <AlertCircle size={14} /> {error}
        </div>
      )}

      <div className="flex justify-end">
        <button
          type="submit"
          disabled={saving || events.length === 0}
          className="px-5 py-2 bg-[#00a884] hover:bg-[#017f67] disabled:opacity-50 text-white text-[14px] font-semibold rounded-lg transition-colors flex items-center gap-2"
        >
          {saving ? <RefreshCw size={14} className="animate-spin" /> : <Plus size={14} />}
          Registrar webhook
        </button>
      </div>
    </form>
  );
}

// ─── Página principal ─────────────────────────────────────────────────────────
export default function WhatsAppWebhooksPage() {
  const [hooks,   setHooks]   = useState<NwWebhook[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try { setHooks(await NwService.getWebhooks()); }
    catch { /* silencioso */ }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  const handleCreated = (hook: NwWebhook) => {
    setHooks(prev => [hook, ...prev]);
    setShowForm(false);
  };

  const handleDelete = (id: string) => setHooks(prev => prev.filter(h => h.id !== id));

  const handleToggle = (id: string, active: boolean) =>
    setHooks(prev => prev.map(h => h.id === id ? { ...h, active } : h));

  return (
    <div className="max-w-3xl mx-auto px-4 py-8 space-y-6">

      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-[#00a884]/10 rounded-xl flex items-center justify-center">
            <Webhook size={20} className="text-[#00a884]" />
          </div>
          <div>
            <h1 className="text-[20px] font-bold text-[#111b21]">Webhooks</h1>
            <p className="text-[13px] text-[#667781]">Push de eventos WhatsApp para sistemas externos</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={load} className="p-2 hover:bg-black/5 rounded-full transition-colors" title="Atualizar">
            <RefreshCw size={16} className={`text-[#54656f] ${loading ? 'animate-spin' : ''}`} />
          </button>
          <button
            onClick={() => setShowForm(v => !v)}
            className="flex items-center gap-2 px-4 py-2 bg-[#00a884] hover:bg-[#017f67] text-white text-[14px] font-semibold rounded-lg transition-colors"
          >
            <Plus size={16} /> Novo webhook
          </button>
        </div>
      </div>

      {/* Formulário de criação */}
      {showForm && <CreateForm onCreated={handleCreated} />}

      {/* Lista */}
      {loading ? (
        <div className="space-y-3">
          {[1, 2].map(i => <div key={i} className="h-16 bg-white rounded-xl border border-[#d1d7db] animate-pulse" />)}
        </div>
      ) : hooks.length === 0 ? (
        <div className="bg-white rounded-xl border border-[#d1d7db] py-16 flex flex-col items-center gap-4 text-[#8696a0]">
          <Webhook size={40} className="opacity-30" />
          <div className="text-center">
            <p className="text-[15px] font-medium text-[#54656f]">Nenhum webhook registrado</p>
            <p className="text-[13px] mt-1">Clique em "Novo webhook" para começar.</p>
          </div>
        </div>
      ) : (
        <div className="space-y-3">
          {hooks.map(h => (
            <WebhookCard key={h.id} hook={h} onDelete={handleDelete} onToggle={handleToggle} />
          ))}
        </div>
      )}

      {/* Info box */}
      <div className="bg-blue-50 border border-blue-100 rounded-xl p-4 text-[13px] text-blue-700 space-y-1">
        <p className="font-semibold flex items-center gap-1.5"><Shield size={13} /> Assinatura HMAC-SHA256</p>
        <p>Cada requisição inclui o header <code className="bg-blue-100 px-1 rounded font-mono text-[12px]">x-nw-signature: sha256=&lt;hmac&gt;</code>.</p>
        <p>Valide com <code className="bg-blue-100 px-1 rounded font-mono text-[12px]">HMAC-SHA256(secret, JSON.stringify(body))</code> antes de processar o payload.</p>
      </div>
    </div>
  );
}
