import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { Printer, ArrowLeft } from "lucide-react";
import { AppShell, BrandMark } from "@/components/AppShell";
import { AiDisclaimer } from "@/components/AiDisclaimer";
import { supabase } from "@/integrations/supabase/client";

export const Route = createFileRoute("/_authenticated/reports/$id")({
  head: () => ({
    meta: [
      { title: "Inspection report | Emma Mold Inspection Services" },
      { name: "description", content: "Your professional mold inspection report with findings and recommendations." },
      { property: "og:title", content: "Inspection report" },
      { property: "og:description", content: "Findings, treatment and recommendations from your inspection." },
      { name: "robots", content: "noindex" },
    ],
  }),
  component: ReportPage,
});

function ReportPage() {
  const { id } = Route.useParams();
  const { data, isLoading } = useQuery({
    queryKey: ["report", id],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("inspection_reports")
        .select("*, report_photos(*)")
        .eq("id", id)
        .maybeSingle();
      if (error) throw error;
      return data;
    },
  });

  if (isLoading) return <AppShell>Loading report…</AppShell>;
  if (!data) return <AppShell>Report not found.</AppShell>;

  const before = data.report_photos?.filter((p) => p.kind === "before") ?? [];
  const after = data.report_photos?.filter((p) => p.kind === "after") ?? [];

  return (
    <AppShell>
      <div className="flex items-center justify-between">
        <Link to="/dashboard" className="inline-flex items-center gap-1 text-xs font-semibold text-muted-foreground">
          <ArrowLeft className="h-3 w-3" /> Back
        </Link>
        <button
          onClick={() => window.print()}
          className="flex items-center gap-2 rounded-xl bg-brand px-4 py-2 text-xs font-semibold text-primary-foreground"
        >
          <Printer className="h-3.5 w-3.5" /> Download PDF
        </button>
      </div>

      <article className="mt-4 rounded-3xl border border-border/60 bg-card p-5 shadow-card">
        <header className="flex items-center gap-3 border-b border-border pb-4">
          <BrandMark className="h-12 w-12" />
          <div>
            <h1 className="text-lg font-bold">Emma Mold Inspection Services</h1>
            <p className="text-xs text-muted-foreground">Inspect. Treat. Protect. Breathe better.</p>
          </div>
        </header>

        <dl className="mt-4 grid grid-cols-2 gap-3 text-xs">
          <Row label="Reference" value={data.reference} />
          <Row label="Inspection date" value={data.inspection_date} />
          <Row label="Inspector" value={data.inspector_name} />
          <Row label="Severity" value={data.severity ?? "—"} />
          <Row label="Property" value={data.property_info ?? "—"} />
        </dl>

        <Section title="Areas inspected" items={data.areas_inspected} />
        <Section title="Likely causes" items={data.likely_causes} />

        {data.ai_assessment ? (
          <>
            <h2 className="mt-5 text-sm font-semibold">AI mold assessment</h2>
            <p className="mt-1 text-sm text-muted-foreground">{data.ai_assessment}</p>
            <AiDisclaimer className="mt-2" />
          </>
        ) : null}

        <h2 className="mt-5 text-sm font-semibold">Measurements</h2>
        <dl className="mt-2 grid grid-cols-2 gap-3 text-xs">
          <Row
            label="🌡️ Temperature"
            value={[data.temperature_level, data.temperature_value ? `${data.temperature_value}°C` : null]
              .filter(Boolean)
              .join(" · ") || "—"}
          />
          <Row
            label="💧 Humidity"
            value={[data.humidity_level, data.humidity_value ? `${data.humidity_value}% RH` : null]
              .filter(Boolean)
              .join(" · ") || "—"}
          />
          <Row label="Moisture reading" value={data.moisture_reading ?? "—"} />
          <Row label="Water detector" value={data.water_detector ?? "—"} />
        </dl>

        <h2 className="mt-5 text-sm font-semibold">Thermal inspection</h2>
        {data.normal_image_url || data.thermal_image_url ? (
          <div className="mt-2 grid grid-cols-2 gap-3">
            <figure>
              <figcaption className="text-[11px] font-semibold uppercase tracking-widest text-primary">Normal</figcaption>
              {data.normal_image_url ? (
                <img src={data.normal_image_url} alt="Normal image" className="mt-1 w-full rounded-xl" loading="lazy" />
              ) : null}
            </figure>
            <figure>
              <figcaption className="text-[11px] font-semibold uppercase tracking-widest text-primary">Thermal</figcaption>
              {data.thermal_image_url ? (
                <img src={data.thermal_image_url} alt="Thermal image" className="mt-1 w-full rounded-xl" loading="lazy" />
              ) : null}
            </figure>
          </div>
        ) : null}
        <p className="mt-1 text-sm text-muted-foreground">
          {data.thermal_notes ?? "No thermal imaging carried out for this inspection."}
        </p>

        <h2 className="mt-5 text-sm font-semibold">Water leakage assessment</h2>
        <p className="mt-1 text-sm text-muted-foreground">
          {data.water_leakage_assessment ?? "No obvious signs detected."}
        </p>
        <p className="mt-1 text-[11px] text-muted-foreground">
          Visual assessment only — not a definitive leak detection.
        </p>

        {data.treatment_performed ? (
          <>
            <h2 className="mt-5 text-sm font-semibold">Treatment performed</h2>
            <p className="mt-1 text-sm text-muted-foreground">{data.treatment_performed}</p>
          </>
        ) : null}

        {before.length || after.length ? (
          <div className="mt-5 grid grid-cols-2 gap-4">
            <PhotoColumn title="Before" photos={before} />
            <PhotoColumn title="After" photos={after} />
          </div>
        ) : null}

        {data.inspector_comments ? (
          <>
            <h2 className="mt-5 text-sm font-semibold">Inspector comments</h2>
            <p className="mt-1 text-sm text-muted-foreground">{data.inspector_comments}</p>
          </>
        ) : null}

        <Section title="Recommendations" items={data.recommendations} />

        <div className="mt-6 border-t border-dashed border-border pt-3 text-xs">
          <p className="text-muted-foreground">Customer signature</p>
          <p className="mt-1 font-semibold">{data.customer_signature ?? "—"}</p>
        </div>

        <footer className="mt-6 border-t border-border pt-4 text-xs text-muted-foreground">
          <p>Signed: {data.signature_name ?? data.inspector_name}</p>
          <p className="mt-1">Emma Mold Inspection Services • hello@emmamold.example • +000 000 0000</p>
        </footer>
      </article>
    </AppShell>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <dt className="text-muted-foreground">{label}</dt>
      <dd className="font-semibold">{value}</dd>
    </div>
  );
}

function Section({ title, items }: { title: string; items: string[] }) {
  if (!items?.length) return null;
  return (
    <>
      <h2 className="mt-5 text-sm font-semibold">{title}</h2>
      <ul className="mt-1 space-y-1 text-sm text-muted-foreground">
        {items.map((i) => (
          <li key={i}>• {i}</li>
        ))}
      </ul>
    </>
  );
}

function PhotoColumn({ title, photos }: { title: string; photos: { id: string; url: string; caption: string | null }[] }) {
  return (
    <div>
      <h3 className="text-xs font-semibold uppercase tracking-widest text-primary">{title}</h3>
      <div className="mt-2 space-y-2">
        {photos.map((p) => (
          <figure key={p.id}>
            <img src={p.url} alt={p.caption ?? `${title} treatment photo`} className="w-full rounded-xl" loading="lazy" />
            {p.caption ? <figcaption className="mt-1 text-[11px] text-muted-foreground">{p.caption}</figcaption> : null}
          </figure>
        ))}
      </div>
    </div>
  );
}