"use client";

import { ArrowLeft, Download } from "lucide-react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import { useAuth } from "@/components/auth";
import { API_BASE } from "@/lib/api";

export default function ValidationPreviewPage() {
  const { token } = useAuth();
  const params = useParams<{ id: string }>();
  const [html, setHtml] = useState("");
  const [message, setMessage] = useState("Vorschau wird geladen.");
  const [toast, setToast] = useState("");

  useEffect(() => {
    if (!token || !params.id) return;
    fetch(`${API_BASE}/validations/${params.id}/report.html`, {
      headers: { Authorization: `Bearer ${token}` }
    })
      .then(async (response) => {
        if (!response.ok) throw new Error(await response.text());
        return response.text();
      })
      .then((content) => {
        setHtml(content);
        setMessage("");
      })
      .catch(() => setMessage("Vorschau konnte nicht geladen werden."));
  }, [params.id, token]);

  async function downloadPdf() {
    const response = await fetch(`${API_BASE}/validations/${params.id}/report.pdf`, {
      headers: { Authorization: `Bearer ${token}` }
    });
    if (!response.ok) {
      const body = await response.json().catch(() => null);
      setToast(body?.detail ?? "PDF konnte nicht erzeugt werden.");
      return;
    }
    const blob = await response.blob();
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "validierungsbericht.pdf";
    link.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="space-y-5">
      <header className="flex flex-col justify-between gap-3 sm:flex-row sm:items-center">
        <div>
          <h1 className="text-3xl font-semibold">HTML-Vorschau</h1>
          <p className="mt-2 text-text-light">Authentifiziert gerenderter Orion-Bericht.</p>
        </div>
        <div className="flex gap-2">
          <Link href="/validations" className="btn btn-secondary h-12"><ArrowLeft className="h-4 w-4" /> Zurueck</Link>
          <button type="button" onClick={downloadPdf} className="btn btn-primary h-12"><Download className="h-4 w-4" /> PDF herunterladen</button>
        </div>
      </header>
      {toast && <div className="fixed right-4 top-4 z-50 max-w-md rounded-lg border border-danger/30 bg-white p-4 text-sm text-danger shadow-soft">{toast}</div>}
      {message ? <div className="rounded-lg border border-border bg-surface p-6 shadow-soft">{message}</div> : <iframe title="Validierungsbericht" srcDoc={html} className="h-[78vh] w-full rounded-lg border border-border bg-white shadow-soft" />}
    </div>
  );
}
