"use client";

import { useEffect, useMemo, useState } from "react";
import { appRelease } from "@/lib/release";

type Inspection = {
  id: string;
  vehicle: string;
  plate: string;
  type: "Leve" | "Moto" | "Pesado";
  stage: string;
  stageTone: "cyan" | "orange" | "green" | "red" | "gray";
  customer: string;
  tenantId?: string;
  time: string;
  score?: number;
  createdAt?: string;
};

type CurrentUser = { name: string; role: string };

const roleLabels: Record<string, string> = {
  capital_admin: "Administrador Capital",
  capital_operator: "Operação Capital",
  analyst: "Analista Capital",
  client_admin: "Administrador do cliente",
  client_manager: "Gestor do cliente",
  integration_user: "Integração",
};

const demoInspections: Inspection[] = [
  { id: "PAN-87421", vehicle: "Toyota Corolla XEi 2023", plate: "RXT-8J21", type: "Leve", stage: "Em análise IA", stageTone: "cyan", customer: "Banco PAN", time: "há 4 min", score: 12 },
  { id: "PAN-87420", vehicle: "Honda CG 160 Titan 2024", plate: "SBA-3C09", type: "Moto", stage: "Em retriagem", stageTone: "orange", customer: "Banco PAN", time: "há 9 min" },
  { id: "CAP-21984", vehicle: "Volvo FH 540 2022", plate: "RMD-7F81", type: "Pesado", stage: "Em análise humana", stageTone: "red", customer: "Capital Demo", time: "há 17 min", score: 46 },
  { id: "PAN-87418", vehicle: "Jeep Compass Limited 2022", plate: "FVP-0A44", type: "Leve", stage: "Aprovada", stageTone: "green", customer: "Banco PAN", time: "há 26 min", score: 8 },
  { id: "PAN-87414", vehicle: "Yamaha Fazer FZ25 2023", plate: "TKS-5H18", type: "Moto", stage: "Link enviado", stageTone: "gray", customer: "Banco PAN", time: "há 38 min" },
];

const statusFilters = ["Todas", "Em análise IA", "Em retriagem", "Em análise humana", "Aprovada", "Link enviado"];

export default function Home() {
  const [activeNav, setActiveNav] = useState("Visão geral");
  const [filter, setFilter] = useState("Todas");
  const [query, setQuery] = useState("");
  const [notice, setNotice] = useState("");
  const [linkBusy, setLinkBusy] = useState("");
  const [inspectionItems, setInspectionItems] = useState<Inspection[]>(demoInspections);
  const [currentUser, setCurrentUser] = useState<CurrentUser | null>(null);

  useEffect(() => {
    fetch("/api/inspections")
      .then(async (response) => response.ok ? response.json() : null)
      .then((data) => {
        if (data?.items) setInspectionItems(data.items);
      })
      .catch(() => undefined);
    fetch("/api/auth/profile")
      .then(async (response) => response.ok ? response.json() : null)
      .then((data) => { if (data?.user) setCurrentUser(data.user); })
      .catch(() => undefined);
  }, []);

  const visible = useMemo(() => inspectionItems.filter((item) => {
    const statusMatches = filter === "Todas" || item.stage === filter;
    const search = `${item.id} ${item.vehicle} ${item.plate} ${item.type}`.toLowerCase();
    return statusMatches && search.includes(query.toLowerCase());
  }), [filter, query, inspectionItems]);
  const live = useMemo(() => { const count = (stages: string[]) => inspectionItems.filter((item) => stages.includes(item.stage)).length; const completed = count(["Aprovada", "Aprovada com ressalvas", "Reprovada"]); const approved = count(["Aprovada", "Aprovada com ressalvas"]); return { inProgress: count(["Em vistoria", "Em análise IA", "Em análise humana", "Em retriagem"]), waiting: count(["Em análise IA", "Em análise humana"]), approval: completed ? `${((approved / completed) * 100).toFixed(1).replace(".", ",")}%` : "—", received: inspectionItems.length, links: count(["Link enviado"]), capture: count(["Em vistoria"]), analysis: count(["Em análise IA", "Em análise humana"]), done: completed }; }, [inspectionItems]);

  function toast(message: string) {
    setNotice(message);
    window.setTimeout(() => setNotice(""), 2600);
  }
  async function generateListLink(item: Inspection) {
    setLinkBusy(item.id);
    try {
      const response = await fetch(`/api/inspections/${encodeURIComponent(item.id)}/link`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ reinspection: item.stage === "Em retriagem", tenantId: item.tenantId }) });
      const result = await response.json();
      if (!response.ok) throw new Error([result.error, result.hint].filter(Boolean).join(" "));
      const url = `${window.location.origin}${result.path}`;
      await navigator.clipboard?.writeText(url);
      toast("Novo link gerado e copiado. Envie-o ao responsável pela vistoria.");
      setInspectionItems((current) => current.map((entry) => entry.id === item.id ? { ...entry, stage: "Link enviado", stageTone: "gray" } : entry));
    } catch (error) { toast(error instanceof Error ? error.message : "Não foi possível gerar o link."); } finally { setLinkBusy(""); }
  }

  return (
    <main className="app-shell"><div className="capital-admin-links"><a href="/admin">Administração</a><a href="/admin/releases">{appRelease.version}</a><a href="/lixeira">Lixeira</a><a href="/perfil">Meu perfil</a><button onClick={async () => { await fetch("/api/auth/logout", { method: "POST" }); window.location.href = "/login"; }}>Sair</button></div>
      <aside className="sidebar">
        <div className="brand"><span className="brand-mark">✓</span><span>GRUPO<br /><b>CAPITAL</b></span></div>
        <div className="workspace"><span className="dot" /> Capital Vistorias <span className="chevron">⌄</span></div>
        <nav aria-label="Menu principal">
          {["Visão geral", "Vistorias", "Fila de exceções", "Regras e decisões", "Integrações", "Clientes", "Relatórios", "Administração"].map((item) => (
            <button key={item} className={activeNav === item ? "nav-item active" : "nav-item"} onClick={() => { if (item === "Fila de exceções") { window.location.href = "/excecoes"; return; } if (item === "Regras e decisões") { window.location.href = "/regras"; return; } if (item === "Integrações") { window.location.href = "/integracoes"; return; } if (item === "Administração") { window.location.href = "/admin"; return; } if (item === "Clientes") { window.location.href = "/admin/clientes"; return; } setActiveNav(item); toast(`${item}: módulo em preparação`); }}>
              <span className="nav-icon">{item === "Visão geral" ? "▦" : item === "Vistorias" ? "◫" : item === "Fila de exceções" ? "!" : item === "Regras e decisões" ? "≋" : item === "Integrações" ? "⌘" : item === "Clientes" ? "◉" : "↗"}</span>{item}
            </button>
          ))}
        </nav>
        <div className="sidebar-bottom"><button className="nav-item" onClick={() => toast("Central de ajuda em preparação")}><span className="nav-icon">?</span>Ajuda e suporte</button><div className="user"><span className="avatar">{(currentUser?.name || "?").split(/\s+/).filter(Boolean).slice(0, 2).map((item) => item[0]).join("").toUpperCase()}</span><span><b>{currentUser?.name || "Carregando..."}</b><small>{roleLabels[currentUser?.role || ""] || "Usuário autenticado"}</small></span><span>⋮</span></div></div>
      </aside>

      <section className="content">
        <header className="topbar"><div className="crumb">Capital Vistorias <span>/</span> {activeNav}</div><div className="top-actions"><button className="icon-button" aria-label="Notificações" onClick={() => toast("Sem novas notificações")}>♧</button><button className="help-button" onClick={() => toast("Vamos estruturar o primeiro módulo juntos.")}>Precisa de ajuda?</button></div></header>
        <div className="page">
          <div className="page-heading"><div><p className="eyebrow">OPERAÇÃO EM TEMPO REAL</p><h1>Visão geral</h1><p className="subheading">Acompanhe a jornada de todas as vistorias e priorize o que exige atenção.</p></div><a className="primary-button" href="/vistorias/nova"><span>＋</span> Nova vistoria</a></div>

          <section className="metric-grid" aria-label="Indicadores da operação">
            <Metric label="Vistorias cadastradas" value={String(live.received)} detail="Total registrado no sistema" />
            <Metric label="Em andamento" value={String(live.inProgress)} detail="Captura, retriagem ou análise" />
            <Metric label="Aguardando análise" value={String(live.waiting)} detail="IA ou análise humana" accent="orange" />
            <Metric label="Taxa de aprovação" value={live.approval} detail="Entre vistorias concluídas" accent="green" />
          </section>

          <section className="insight-grid">
            <div className="panel flow-panel"><div className="panel-title"><div><p className="eyebrow">FLUXO DE OPERAÇÃO</p><h2>Vistorias por etapa</h2></div><button className="text-button" onClick={() => setActiveNav("Vistorias")}>Ver todas →</button></div><div className="funnel">{[["Recebidas", live.received, "#8bd9ea"], ["Link enviado", live.links, "#51c7e1"], ["Em vistoria", live.capture, "#16afd0"], ["Em análise", live.analysis, "#0b83ab"], ["Concluídas", live.done, "#0a3c55"]].map(([label, value, color], index) => <div className="funnel-row" key={String(label)}><span>{label}</span><div className="funnel-track"><div style={{ width: live.received ? `${Math.max(4, (Number(value) / live.received) * 100)}%` : "4%", background: String(color) }} /></div><b>{value}</b></div>)}</div></div>
            <div className="panel attention-panel"><div className="panel-title"><div><p className="eyebrow">PRIORIDADE</p><h2>Requer atenção</h2></div><span className="count">{live.waiting + inspectionItems.filter((item) => item.stage === "Em retriagem").length}</span></div><div className="alert-item"><span className="alert-icon warning">!</span><div><b>Fotos pendentes de retriagem</b><p>{inspectionItems.filter((item) => item.stage === "Em retriagem").length} vistorias aguardam nova captura.</p></div><a href="/excecoes">Ver fila</a></div><div className="alert-item"><span className="alert-icon danger">!</span><div><b>Casos aguardando análise</b><p>{live.waiting} vistorias aguardam IA ou análise humana.</p></div><a href="/excecoes">Ver fila</a></div></div>
          </section>

          <section className="panel list-panel"><div className="panel-title list-title"><div><p className="eyebrow">ACOMPANHAMENTO</p><h2>Vistorias recentes</h2></div><div className="view-switch"><button className="selected" aria-label="Visualização em lista">☷</button><button aria-label="Visualização em cards" onClick={() => toast("A visão em cards entra na próxima iteração")}>▦</button></div></div><div className="toolbar"><div className="search"><span>⌕</span><input aria-label="Buscar vistoria" placeholder="Buscar por placa, proposta ou veículo" value={query} onChange={(event) => setQuery(event.target.value)} /></div><div className="filters">{statusFilters.slice(0, 4).map((item) => <button key={item} className={filter === item ? "filter active-filter" : "filter"} onClick={() => setFilter(item)}>{item}</button>)}</div></div><div className="table-wrap"><table><thead><tr><th>Proposta</th><th>Veículo</th><th>Tipo</th><th>Status</th><th>Cliente</th><th>Atualização</th><th /></tr></thead><tbody>{visible.map((item) => { const href = `/vistorias/${encodeURIComponent(item.id)}${item.tenantId ? `?tenantId=${encodeURIComponent(item.tenantId)}` : ""}`; return <tr className="inspection-clickable-row" key={`${item.tenantId}-${item.id}`} tabIndex={0} role="link" aria-label={`Abrir vistoria ${item.id}`} onClick={() => { window.location.href = href; }} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); window.location.href = href; } }}><td><a className="inspection-cell-link" href={href}><b>{item.id}</b><small>{item.plate}</small></a></td><td><a className="inspection-cell-link vehicle-link" href={href}>{item.vehicle}{item.score !== undefined && <small>Índice de risco: {item.score} pts</small>}</a></td><td><span className={`vehicle-tag ${item.type.toLowerCase()}`}>{item.type}</span></td><td><span className={`status ${item.stageTone}`}><i />{item.stage}</span></td><td>{item.customer}</td><td>{item.time}</td><td>{item.stage === "Em retriagem" ? <button className="row-action view-button retriage-link-button" disabled={linkBusy === item.id} onClick={(event) => { event.stopPropagation(); generateListLink(item); }}>{linkBusy === item.id ? "Gerando..." : "Gerar novo link"}</button> : <a className="row-action view-button" href={href}>Ver vistoria →</a>}</td></tr>; })}</tbody></table></div></section>

          <section className="foundation"><div><p className="eyebrow">MVP EM CONSTRUÇÃO</p><h2>Base pronta para leves, motos e pesados.</h2><p>O tipo de veículo definirá roteiro de fotos, regras, campos de integração e modelo de laudo. No MVP PAN, leves e motos entram desde o início.</p></div><div className="foundation-tags"><span>Leves</span><span>Motos</span><span>Pesados</span></div></section>
        </div>
      </section>
      {notice && <div className="toast" role="status">{notice}</div>}
    </main>
  );
}

function Metric({ label, value, detail, trend, accent = "cyan" }: { label: string; value: string; detail: string; trend?: "up"; accent?: string }) {
  return <article className={`metric ${accent}`}><p>{label}</p><strong>{value}</strong><span className={trend ? "positive" : ""}>{trend ? "↗ " : ""}{detail}</span></article>;
}
