import { Eye, Loader2 } from "lucide-react";
import { useEffect, useState } from "react";
import { DownloadButton } from "./blocks";
import { FormError } from "./form";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { fetchFile } from "@/api/http";

const TYPES: Record<string, string> = {
  pdf: "application/pdf",
  jpg: "image/jpeg",
  jpeg: "image/jpeg",
  png: "image/png",
  csv: "text/plain",
  txt: "text/plain",
};
/** An evidence file: opens inside the page when the browser can show it, and can always be downloaded. */
export function EvidenceFile({ path, name }: { path: string; name: string }) {
  const [open, setOpen] = useState(false);
  const type = TYPES[name.split(".").at(-1)?.toLowerCase() ?? ""];
  if (!type) return <DownloadButton path={path}>{name}</DownloadButton>;
  return (
    <>
      <Button type="button" size="sm" variant="outline" onClick={() => setOpen(true)}>
        <Eye />
        {name}
      </Button>
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="flex h-[90vh] max-w-5xl flex-col">
          <DialogHeader>
            <DialogTitle className="truncate pr-8">{name}</DialogTitle>
          </DialogHeader>
          {open && <Preview path={path} type={type} name={name} />}
          <div className="flex justify-end">
            <DownloadButton path={path}>Download</DownloadButton>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
function Preview({ path, type, name }: { path: string; type: string; name: string }) {
  const [url, setUrl] = useState("");
  const [text, setText] = useState("");
  const [error, setError] = useState<Error>();
  useEffect(() => {
    let made = "";
    let live = true;
    fetchFile(path)
      .then(async ({ blob }) => {
        if (!live) return;
        if (type === "text/plain") return setText((await blob.text()).slice(0, 200_000));
        // The type is ours, never the one the file claims, so a file can never run as a web page.
        made = URL.createObjectURL(new Blob([blob], { type }));
        setUrl(made);
      })
      .catch((e: Error) => {
        if (live) setError(e);
      });
    return () => {
      live = false;
      if (made) URL.revokeObjectURL(made);
    };
  }, [path, type]);
  if (error)
    return (
      <div className="flex-1">
        <FormError error={error} />
      </div>
    );
  if (text)
    return (
      <pre className="min-h-0 flex-1 overflow-auto rounded-lg border bg-surface-2 p-3 text-[12px]">
        {text}
      </pre>
    );
  if (!url)
    return (
      <div className="grid flex-1 place-items-center" role="status" aria-label="Loading">
        <Loader2 className="animate-spin" />
      </div>
    );
  return type === "application/pdf" ? (
    <iframe src={url} title={name} className="min-h-0 w-full flex-1 rounded-lg border" />
  ) : (
    <div className="grid min-h-0 flex-1 place-items-center overflow-auto rounded-lg border bg-surface-2">
      <img src={url} alt={name} className="max-h-full max-w-full object-contain" />
    </div>
  );
}
