"use client";

import { type CSSProperties, useEffect, useState } from "react";
import { useParams } from "next/navigation";

type Inspection = { external_id: string; vehicle_description: string | null; vehicle_type: string; plate: string; model_year: number | null; status: string; created_at: string };
type Photo = { id: string; category_code: string; ai_status: string; analysis_status?: string | null; analysis_summary?: string | null; analysis_findings?: string[] | string | null; analysis_requires_human?: number | boolean | null; manual_assessment?: string | null; manual_damage_location?: string | null; manual_comments?: string | null; manual_analyst_name?: string | null; human_comments?: string | null };
type Profile = { client_can_view_photos: number | boolean; client_can_manual_review: number | boolean; client_can_download_report: number | boolean };
type Review = { analyst_name: string; decision: string; comments: string; reason: string; completed_at: string };
type Branding = { displayName: string; logoUrl: string | null; primaryColor: string; accentColor: string; backgroundColor: string };
const labels: Record<string, string> = { received: "Recebida", link_sent: "Link enviado", in_progress: "Em vistoria", retriage: "Com apontamento · retriagem", ai_analysis: "Em análise", human_review: "Com apontamento · análise humana", approved: "Sem apontamentos · aprovada", approved_with_notes: "Com apontamentos · aprovada", rejected: "Recusada · reprovada", expired: "Frustrada · link expirado", cancelled: "Frustrada · cancelada" };
const statusTone = (status: string) => status === "approved" ? "success" : ["approved_with_notes", "retriage", "human_review", "pending_data"].includes(status) ? "attention" : ["rejected", "expired", "cancelled"].includes(status) ? "critical" : "neutral";
const manualAssessmentLabels: Record<string, string> = { no_damage: "Sem avaria ou divergência", damage_light: "Avaria leve", damage_moderate: "Avaria moderada", damage_severe: "Avaria grave", damage_structural: "Avaria estrutural/crítica", plate_divergent: "Placa divergente", chassis_divergent: "Chassi divergente/adulterado" };
function photoTone(photo: Photo) {
  if (["damage_structural", "chassis_divergent"].includes(String(photo.manual_assessment))) return "critical";
  if (["damage_light", "damage_moderate", "damage_severe", "plate_divergent"].includes(String(photo.manual_assessment))) return "attention";
  if (photo.manual_assessment === "no_damage" || photo.ai_status === "accepted") return "success";
  if (photo.ai_status === "retriage") return "critical";
  if (photo.analysis_status === "requires_human" || photo.ai_status === "flagged") return "attention";
  return "neutral";
}
function photoStatusLabel(photo: Photo) { const tone = photoTone(photo); return tone === "success" ? "Sem apontamentos" : tone === "attention" ? "Com apontamento" : tone === "critical" ? "Recusada" : "Em análise"; }
function parseFindings(value: Photo["analysis_findings"]) { if (Array.isArray(value)) return value.map(String); if (typeof value !== "string") return []; try { const parsed = JSON.parse(value); return Array.isArray(parsed) ? parsed.map(String) : []; } catch { return []; } }

export default function ClientInspectionPage() {
  const { externalId } = useParams<{ externalId: string }>(); const [inspection, setInspection] = useState<Inspection | null>(null), [photos, setPhotos] = useState<Photo[]>([]), [profile, setProfile] = useState<Profile | null>(null), [review, setReview] = useState<Review | null>(null), [error, setError] = useState(""), [open, setOpen] = useState(false), [decision, setDecision] = useState("approved"), [reason, setReason] = useState(""), [comments, setComments] = useState(""), [message, setMessage] = useState(""), [branding, setBranding] = useState<Branding | null>(null);
  useEffect(() => { fetch(`/api/client/inspections/${encodeURIComponent(externalId)}`).then(async r => ({ r, b: await r.json() })).then(({ r, b }) => { if (!r.ok) throw new Error([b.error, b.hint].filter(Boolean).join(" ")); setInspection(b.inspection); setPhotos(b.photos ?? []); setProfile(b.profile); setReview(b.review); }).catch(e => setError(e instanceof Error ? e.message : "Não foi possível carregar.")); }, [externalId]);
  useEffect(() => { fetch("/api/client/branding").then(response => response.ok ? response.json() : null).then(data => { if (data?.branding) setBranding(data.branding); }).catch(() => undefined); }, []);
  async function submit(e: React.FormEvent<HTMLFormElement>) { e.preventDefault(); setMessage("Registrando decisão..."); try { const r = await fetch(`/api/client/inspections/${encodeURIComponent(externalId)}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ decision, reason, comments }) }); const b = await r.json(); if (!r.ok) throw new Error(b.error); setMessage("Decisão registrada."); window.setTimeout(() => window.location.reload(), 650); } catch (e) { setMessage(e instanceof Error ? e.message : "Não foi possível registrar."); } }
  if (error) return <main className="client-detail"><a href="/cliente">← Voltar ao portal</a><div className="client-detail-error"><b>Não foi possível abrir esta vistoria</b><p>{error}</p></div></main>;
  if (!inspection || !profile) return <main className="client-detail"><p className="eyebrow">CARREGANDO</p><h1>Buscando vistoria...</h1></main>;
  const canReview = Boolean(profile.client_can_manual_review), canDownload = Boolean(profile.client_can_download_report) && ["approved", "approved_with_notes", "rejected"].includes(inspection.status);
  const brandStyle = branding ? { "--client-primary": branding.primaryColor, "--client-accent": branding.accentColor, "--client-background": branding.backgroundColor } as CSSProperties : undefined;
  return <main className="client-detail" style={brandStyle}><header><a className="client-brand" href="/cliente">{branding?.logoUrl ? <img className="client-brand-logo" src={`${branding.logoUrl}?v=${encodeURIComponent(branding.primaryColor)}`} alt={`Logo ${branding.displayName}`} /> : <><span>✓</span><b>{branding?.displayName || "Portal do cliente"}</b><i>·</i> Autovistoria Veicular</>}</a><a href="/cliente">← Minhas vistorias</a></header><section className="client-detail-wrap"><div className="client-detail-title"><div><p className="eyebrow">VISTORIA {inspection.vehicle_type.toUpperCase()}</p><h1>{inspection.vehicle_description || "Veículo não informado"}</h1><p>{inspection.plate} · Proposta {inspection.external_id} · {inspection.model_year || "Ano não informado"}</p></div><span className={`client-detail-status ${statusTone(inspection.status)}`}>{labels[inspection.status] ?? inspection.status}</span></div><section className="client-progress"><span className="done">1<small>Solicitação</small></span><i /><span className="done">2<small>Vistoria</small></span><i /><span className={photos.length ? "done" : ""}>3<small>Análise</small></span><i /><span className={canDownload ? "done" : ""}>4<small>Laudo</small></span></section><div className="client-detail-grid"><div><section className="client-detail-card"><div className="client-card-head"><div><p className="eyebrow">FOTOS DA VISTORIA</p><h2>Roteiro enviado</h2></div><span>{photos.length} fotos</span></div>{Boolean(profile.client_can_view_photos) ? <div className="client-photo-grid">{photos.map(p => { const findings = parseFindings(p.analysis_findings); const tone = photoTone(p); const hasAiComment = Boolean(p.analysis_summary || findings.length); const hasHumanComment = Boolean(p.manual_assessment || p.manual_comments || p.human_comments); return <article className={`client-photo-card ${tone}`} key={p.id}><a href={`/api/inspections/${encodeURIComponent(inspection.external_id)}/photos/${p.id}`} target="_blank" rel="noreferrer"><img src={`/api/inspections/${encodeURIComponent(inspection.external_id)}/photos/${p.id}`} alt={p.category_code} /></a><div className="client-photo-content"><div className="client-photo-heading"><b>{p.category_code}</b><span className={`client-photo-status ${tone}`}>{photoStatusLabel(p)}</span></div>{hasAiComment && <section className="client-photo-comment ai"><strong>Análise por IA</strong>{p.analysis_summary && <p>{p.analysis_summary}</p>}{findings.length > 0 && <ul>{findings.map((finding, index) => <li key={`${p.id}-${index}`}>{finding}</li>)}</ul>}</section>}{hasHumanComment && <section className="client-photo-comment human"><strong>Avaliação humana{p.manual_analyst_name ? ` · ${p.manual_analyst_name}` : ""}</strong>{p.manual_assessment && <p><b>{manualAssessmentLabels[p.manual_assessment] ?? "Avaliação registrada"}</b>{p.manual_damage_location ? ` · ${p.manual_damage_location}` : ""}</p>}{p.manual_comments && <p>{p.manual_comments}</p>}{p.human_comments && <p className="client-photo-analyst-comments">{p.human_comments}</p>}</section>}{!hasAiComment && !hasHumanComment && <small>Foto recebida; análise em processamento.</small>}</div></article>; })}</div> : <p className="client-restricted">A visualização das fotos não está habilitada para este cliente.</p>}</section>{review ? <section className={`client-detail-card client-review-result ${statusTone(review.decision)}`}><p className="eyebrow">DECISÃO REGISTRADA</p><h2>{labels[review.decision] ?? review.decision}</h2><p>{review.reason}</p><small>Registrada por {review.analyst_name} em {new Date(review.completed_at).toLocaleString("pt-BR")}</small></section> : canReview ? <section className="client-detail-card"><div className="client-card-head"><div><p className="eyebrow">ANÁLISE MANUAL</p><h2>Decisão do cliente</h2></div><span className="client-enabled">Habilitada</span></div>{open ? <form className="client-review-form" onSubmit={submit}><label>Decisão<select value={decision} onChange={e => setDecision(e.target.value)}><option value="approved">Aprovar</option><option value="approved_with_notes">Aprovar com ressalvas</option><option value="retriage">Solicitar retriagem</option><option value="rejected">Reprovar</option></select></label><label>Motivo da decisão<textarea value={reason} onChange={e => setReason(e.target.value)} required /></label><label>Comentários técnicos<textarea value={comments} onChange={e => setComments(e.target.value)} required /></label><div><small>{message}</small><button>Registrar decisão</button></div></form> : <div className="client-manual-cta"><p>Seu perfil permite registrar uma decisão manual para esta vistoria.</p><button onClick={() => setOpen(true)}>Iniciar análise manual</button></div>}</section> : <section className="client-detail-card client-review-restricted"><p className="eyebrow">ANÁLISE MANUAL</p><h2>Disponível para a Capital</h2><p>Este cliente acompanha fotos, status e laudo, mas não altera a decisão técnica.</p></section>}</div><aside><section className={`client-side-card client-status-card ${statusTone(inspection.status)}`}><p className="eyebrow">STATUS ATUAL</p><h2>{labels[inspection.status] ?? inspection.status}</h2><p>A Capital acompanha esta vistoria. O laudo será disponibilizado quando a decisão for conclusiva.</p><div><span>Solicitação</span><b>{new Date(inspection.created_at).toLocaleString("pt-BR")}</b></div></section><section className="client-side-card"><p className="eyebrow">LAUDO</p><h2>{canDownload ? "Disponível" : "Em preparação"}</h2><p>{canDownload ? "O laudo técnico foi liberado para download." : "O PDF será liberado após uma decisão conclusiva."}</p>{canDownload ? <a className="client-report-download" href={`/api/inspections/${encodeURIComponent(inspection.external_id)}/report`} target="_blank" rel="noreferrer">Baixar PDF ↓</a> : <button disabled>Baixar PDF</button>}</section></aside></div></section></main>;
}
