"use client";

import { useEffect, useState } from "react";

type Tenant = { id: string; name: string };
type Connection = { id: string; tenant_id: string; tenant_name: string; name: string; direction: "inbound" | "outbound"; status: string; endpoint_url: string | null; auth_type: string; credential_reference: string | null; deliveries: number | string; updated_at: string };

export default function IntegrationsPage() {
  const [tenants, setTenants] = useState<Tenant[]>([]);
  const [connections, setConnections] = useState<Connection[]>([]);
  const [message, setMessage] = useState("");
  const [createdKey, setCreatedKey] = useState("");
  const [form, setForm] = useState({ tenantId: "", name: "API de solicitações", direction: "inbound", endpointUrl: "", authType: "api_key", credentialReference: "" });

  async function load() {
    try {
      const response = await fetch("/api/admin/integrations");
      const body = await response.json();
      if (!response.ok) throw new Error([body.error, body.hint].filter(Boolean).join(" "));
      setTenants(body.tenants || []); setConnections(body.connections || []);
      if (!form.tenantId && body.tenants?.[0]) setForm(current => ({ ...current, tenantId: body.tenants[0].id }));
    } catch (error) { setMessage(error instanceof Error ? error.message : "Não foi possível carregar integrações."); }
  }
  useEffect(() => { void load(); }, []);

  async function create(event: React.FormEvent) {
    event.preventDefault(); setMessage("Salvando integração..."); setCreatedKey("");
    try {
      const response = await fetch("/api/admin/integrations", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form) });
      const body = await response.json();
      if (!response.ok) throw new Error([body.error, body.hint].filter(Boolean).join(" "));
      setMessage(body.message); setCreatedKey(body.apiKey || "");
      setForm(current => ({ ...current, name: current.direction === "inbound" ? "API de solicitações" : "Retorno de laudos", endpointUrl: "", credentialReference: "" }));
      await load();
    } catch (error) { setMessage(error instanceof Error ? error.message : "Não foi possível salvar."); }
  }
  async function copy(value: string) { await navigator.clipboard?.writeText(value); setMessage("Copiado para a área de transferência."); }
  async function regenerate(connection: Connection) {
    if (!window.confirm(`Gerar uma nova chave para “${connection.name}”? A chave atual será revogada imediatamente.`)) return;
    setMessage("Gerando nova chave..."); setCreatedKey("");
    try {
      const response = await fetch("/api/admin/integrations", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "regenerate", connectionId: connection.id }) });
      const body = await response.json();
      if (!response.ok) throw new Error(body.error || "Não foi possível gerar a nova chave.");
      setCreatedKey(body.apiKey); setMessage(body.message); await load();
    } catch (error) { setMessage(error instanceof Error ? error.message : "Não foi possível gerar a nova chave."); }
  }
  const origin = typeof window === "undefined" ? "" : window.location.origin;

  return <main className="integrations-page">
    <header className="rules-header"><a href="/">← Dashboard Capital</a><div><a href="/integracoes/simulador">Simular origem externa</a><a href="/regras">Regras e decisões</a><a href="/admin">Administração</a></div></header>
    <div className="rules-heading"><div><p className="eyebrow">CENTRAL DE INTEGRAÇÕES</p><h1>APIs e conectores</h1><p>Crie um acesso de API exclusivo por cliente para receber solicitações. Configure também o destino que receberá laudos e decisões quando a especificação do cliente estiver disponível.</p></div></div>
    <div className="integrations-grid"><section className="integration-form-card"><p className="eyebrow">NOVA CONEXÃO</p><h2>Configurar integração</h2><form onSubmit={create}><label>Cliente<select value={form.tenantId} onChange={event => setForm({ ...form, tenantId: event.target.value })} required>{tenants.map(tenant => <option key={tenant.id} value={tenant.id}>{tenant.name}</option>)}</select></label><label>Nome da conexão<input value={form.name} onChange={event => setForm({ ...form, name: event.target.value })} required /></label><label>Direção<select value={form.direction} onChange={event => setForm({ ...form, direction: event.target.value, name: event.target.value === "inbound" ? "API de solicitações" : "Retorno de laudos", authType: event.target.value === "inbound" ? "api_key" : "bearer" })}><option value="inbound">Entrada — receber solicitações</option><option value="outbound">Saída — enviar decisão/laudo</option></select></label>{form.direction === "outbound" && <><label>URL de destino<input type="url" placeholder="https://api.cliente.com/laudos" value={form.endpointUrl} onChange={event => setForm({ ...form, endpointUrl: event.target.value })} required /></label><label>Autenticação<select value={form.authType} onChange={event => setForm({ ...form, authType: event.target.value })}><option value="bearer">Bearer token</option><option value="api_key">API key</option><option value="none">Sem autenticação</option></select></label><label>Referência da credencial<input placeholder="Ex.: PAN_OUTBOUND_TOKEN" value={form.credentialReference} onChange={event => setForm({ ...form, credentialReference: event.target.value })}/><small>A senha/token não é armazenada no banco. Use aqui apenas o nome da variável configurada no servidor.</small></label></>}</form><button className="integration-save" onClick={() => document.querySelector<HTMLFormElement>(".integration-form-card form")?.requestSubmit()}>Criar conexão</button></section>
      <aside className="integration-help"><p className="eyebrow">PADRÃO DE ENTRADA</p><h2>Receber uma vistoria</h2><p>O cliente envia uma solicitação JSON autenticada. A chave é exclusiva por conexão e exibida apenas no momento da criação.</p><code>POST /api/public/v1/inspections</code><p className="integration-fields">Campos: <b>externalId, vehicleType, plate, chassis, responsibleName, responsiblePhone</b>. Também aceita responsibleEmail, deliveryChannel, vehicleDescription e modelYear.</p><p>Ao receber a solicitação, o sistema cria a vistoria e o link seguro. O disparo automático ocorre quando o broker de mensageria do cliente estiver configurado.</p><p>Autenticação: <b>Authorization: Bearer &lt;chave&gt;</b> ou <b>X-API-Key</b>.</p></aside></div>
    {createdKey && <section className="integration-key"><div><p className="eyebrow">CHAVE GERADA — EXIBA UMA ÚNICA VEZ</p><h2>Guarde esta chave em local seguro</h2><code>{createdKey}</code><small>Endpoint: {origin}/api/public/v1/inspections</small></div><button onClick={() => copy(createdKey)}>Copiar chave</button></section>}
    {message && <p className="rules-message">{message}</p>}
    <section className="integration-list"><div><p className="eyebrow">CONEXÕES CADASTRADAS</p><h2>Clientes e destinos</h2></div>{connections.length ? connections.map(connection => <article key={connection.id}><span className={connection.direction === "inbound" ? "integration-direction inbound" : "integration-direction outbound"}>{connection.direction === "inbound" ? "↓" : "↑"}</span><div><b>{connection.name}</b><small>{connection.tenant_name} · {connection.direction === "inbound" ? "Recebimento de solicitações" : connection.endpoint_url || "Destino não informado"}</small></div><div className="integration-meta"><span>{connection.auth_type}</span><span>{Number(connection.deliveries)} registros</span></div>{connection.direction === "inbound" && <button className="integration-regenerate" onClick={() => regenerate(connection)}>Nova chave</button>}<strong className={connection.status === "active" ? "integration-active" : "integration-inactive"}>{connection.status === "active" ? "Ativa" : "Inativa"}</strong></article>) : <p className="integration-empty">Nenhuma conexão cadastrada.</p>}</section>
  </main>;
}
