"use client";

import { useEffect, useState } from "react";

type Item = { external_id: string; vehicle_type: "light" | "motorcycle" | "heavy"; plate: string; vehicle_description: string | null; risk_score: number | string; trashed_at: string; trashed_by: string | null; tenant_id: string };
const typeLabel = { light: "Leve", motorcycle: "Moto", heavy: "Pesado" };

export default function TrashPage() {
  const [items, setItems] = useState<Item[]>([]); const [message, setMessage] = useState(""); const [busy, setBusy] = useState("");
  const load = async () => { try { const response = await fetch("/api/trash"); const body = await response.json(); if (!response.ok) throw new Error([body.error, body.hint].filter(Boolean).join(" ")); setItems(body.items || []); } catch (error) { setMessage(error instanceof Error ? error.message : "Não foi possível carregar a lixeira."); } };
  useEffect(() => { void load(); }, []);
  async function restore(item: Item) { const key = `${item.tenant_id}-${item.external_id}`; setBusy(key); setMessage(""); try { const response = await fetch(`/api/inspections/${encodeURIComponent(item.external_id)}/trash`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "restore", tenantId: item.tenant_id }) }); const body = await response.json(); if (!response.ok) throw new Error([body.error, body.hint].filter(Boolean).join(" ")); setItems((current) => current.filter((entry) => entry.tenant_id !== item.tenant_id || entry.external_id !== item.external_id)); setMessage(body.message); } catch (error) { setMessage(error instanceof Error ? error.message : "Não foi possível restaurar a vistoria."); } finally { setBusy(""); } }
  return <main className="trash-page"><header className="trash-header"><a className="mini-brand" href="/"><span>✓</span> GRUPO <b>CAPITAL</b></a><a href="/">← Voltar ao dashboard</a></header><section className="trash-wrap"><div className="trash-heading"><div><p className="eyebrow">ARQUIVAMENTO SEGURO</p><h1>Lixeira de vistorias</h1><p>As vistorias ficam preservadas com fotos e histórico. Ao restaurar, gere um novo link antes de enviá-lo ao responsável.</p></div><button onClick={load}>↻ Atualizar</button></div>{message && <div className="trash-message">{message}</div>}<section className="trash-list">{items.length === 0 ? <div className="trash-empty"><b>A lixeira está vazia.</b><p>Nenhuma vistoria arquivada no momento.</p></div> : items.map((item) => { const key = `${item.tenant_id}-${item.external_id}`; return <article key={key}><span className="trash-icon">⌫</span><div><b>{item.external_id}</b><h2>{item.vehicle_description || "Veículo não informado"}</h2><p>{item.plate} · {typeLabel[item.vehicle_type]} · Risco {Number(item.risk_score)} pts</p><small>Movida por {item.trashed_by || "usuário"} em {new Date(item.trashed_at).toLocaleString("pt-BR")}</small></div><button disabled={busy === key} onClick={() => restore(item)}>{busy === key ? "Restaurando..." : "Restaurar vistoria"}</button></article>; })}</section></section></main>;
}
