import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { PageShell } from "@/components/page-shell";
import { downloadText } from "@/lib/srt";
import { ensureAnonymousSession } from "@/lib/ensure-session";
import { FileText, Music, Trash2 } from "lucide-react";

export const Route = createFileRoute("/history")({
  head: () => ({ meta: [{ title: "History — Gatavase AI Creative" }, { name: "robots", content: "noindex" }] }),
  component: HistoryPage,
});

type Project = {
  id: string; kind: string; title: string; output_text: string | null;
  file_url: string | null; transcript: string | null; created_at: string;
};

function HistoryPage() {
  const [items, setItems] = useState<Project[] | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => { void load(); }, []);
  async function load() {
    await ensureAnonymousSession();
    try {
      const { listProjects } = await import("@/lib/history.functions");
      setItems(await listProjects());
    } catch (e) { setError(e instanceof Error ? e.message : "Failed to load"); }
  }
  async function remove(id: string) {
    if (!confirm("Delete this project?")) return;
    const { deleteProject } = await import("@/lib/history.functions");
    await deleteProject({ data: { id } });
    setItems((it) => it?.filter((x) => x.id !== id) ?? null);
  }

  return (
    <PageShell eyebrow="Your work" title="History" lead="Every document, audio and generation you've saved.">
      <div className="mb-4"><Link to="/studio" className="text-sm text-primary underline">← Back to Studio</Link></div>
      {error && <div className="mb-4 rounded-lg border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive">{error}</div>}
      {items === null ? <div className="text-sm text-muted-foreground">Loading…</div> :
        items.length === 0 ? (
          <div className="glow-card rounded-2xl p-8 text-center text-sm text-muted-foreground">
            No saved projects yet. Generate something in a tool and click <b>Save to History</b>.
          </div>
        ) : (
          <div className="grid gap-4">
            {items.map((p) => (
              <div key={p.id} className="glow-card rounded-2xl p-5">
                <div className="flex items-start justify-between gap-4">
                  <div className="min-w-0">
                    <div className="flex items-center gap-2 text-xs uppercase tracking-widest text-muted-foreground">
                      {p.file_url ? <Music className="h-3 w-3" /> : <FileText className="h-3 w-3" />}
                      {p.kind} · {new Date(p.created_at).toLocaleString()}
                    </div>
                    <h3 className="mt-1 font-display text-lg font-semibold">{p.title}</h3>
                  </div>
                  <button onClick={() => remove(p.id)} className="rounded-lg border border-border/60 p-2 text-muted-foreground hover:text-destructive" aria-label="Delete">
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
                {p.file_url && <audio controls src={p.file_url} className="mt-3 w-full" />}
                {p.output_text && (
                  <details className="mt-3">
                    <summary className="cursor-pointer text-sm text-primary">View content</summary>
                    <pre className="mt-2 max-h-64 overflow-auto rounded-lg bg-background/40 p-3 text-xs whitespace-pre-wrap">{p.output_text}</pre>
                  </details>
                )}
                <div className="mt-3 flex flex-wrap gap-2">
                  {p.output_text && (
                    <button onClick={() => downloadText(`${slug(p.title)}.txt`, p.output_text!)} className="rounded-lg border border-border/60 px-3 py-1.5 text-xs">Download TXT</button>
                  )}
                  {p.transcript && (
                    <button onClick={() => downloadText(`${slug(p.title)}.srt`, p.transcript!)} className="rounded-lg border border-border/60 px-3 py-1.5 text-xs">Download SRT</button>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
    </PageShell>
  );
}
const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "file";
