"use client";

import { useMemo, useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { LinkIcon } from "lucide-react";
import { PdfViewer } from "@/components/pdf";

export interface PdfFactProps {
  file: string;
  title: string;
  page: string;
  bbox: [number, number, number, number];
  node_id?: string;
  children?: React.ReactNode;
}

export function PdfFact({ file, title, page, bbox, node_id, children }: PdfFactProps) {
  const text = children ? children : title;
  const bbox_str = `[${bbox[0]},${bbox[1]},${bbox[2]},${bbox[3]}]`;
  const pdfUrl = `/api/pdfref/serve_pdf?file=${encodeURIComponent(file)}`;
  const referencePage = Number.parseInt(page, 10) || 1;
  const [open, setOpen] = useState(false);
  const [numPages, setNumPages] = useState<number | null>(null);
  const [currentPage, setCurrentPage] = useState(referencePage);

  const safeCurrentPage = useMemo(() => {
    const p = Number.isFinite(currentPage) ? Math.floor(currentPage) : referencePage;
    if (!numPages) return Math.max(1, p);
    return Math.min(Math.max(1, p), numPages);
  }, [currentPage, numPages, referencePage]);

  // Keep this around for future bbox-overlay work.
  const _imgSrc = node_id
    ? `/api/pdfref/render_bbox?node_id=${encodeURIComponent(node_id)}`
    : `/api/pdfref/render_bbox?file=${encodeURIComponent(
        file,
      )}&page=${encodeURIComponent(page)}&bbox=${encodeURIComponent(bbox_str)}`;

  const boxes = [
    {
      id: "ref",
      label: title,
      // Assumes Docling/PDF coordinate space: [l, t, r, b] (origin=BOTTOMLEFT)
      bbox,
      color: "#ef4444",
    },
  ] as const;

  const showRefBoxes = safeCurrentPage === referencePage;
  return (
    <Dialog
      open={open}
      onOpenChange={(next) => {
        setOpen(next);
        if (next) {
          // Reset when opening so it always starts at the referenced page.
          setCurrentPage(referencePage);
        }
      }}
    >
      <DialogTrigger asChild>
        <button className="inline-flex items-center gap-1 underline underline-offset-2">
          <LinkIcon className="h-3.5 w-3.5" />
          {text}
        </button>
      </DialogTrigger>
      <DialogContent className="flex h-[90vh] w-[calc(70vw-2rem)] max-w-[calc(100vw-2rem)] flex-col gap-0 p-0 sm:max-w-[calc(100vw-2rem)]">
        <DialogHeader className="shrink-0 border-b p-4">
          <DialogTitle className="truncate">
            {file}: {page} {title}
          </DialogTitle>
          <DialogDescription className="truncate">
            PDF reference viewer
          </DialogDescription>
        </DialogHeader>

        <div className="min-h-0 flex-1 p-2">
          <div className="h-full overflow-auto rounded-md border">
            <div className="flex min-h-full flex-col gap-2 p-2">
              <div className="flex flex-wrap items-center gap-2">
                <button
                  type="button"
                  className="rounded-md border px-2 py-1 text-xs disabled:opacity-50"
                  onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                  disabled={safeCurrentPage <= 1}
                >
                  Prev
                </button>
                <button
                  type="button"
                  className="rounded-md border px-2 py-1 text-xs disabled:opacity-50"
                  onClick={() => setCurrentPage((p) => p + 1)}
                  disabled={numPages != null ? safeCurrentPage >= numPages : false}
                >
                  Next
                </button>

                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <span>Page</span>
                  <input
                    type="number"
                    inputMode="numeric"
                    min={1}
                    max={numPages ?? undefined}
                    value={safeCurrentPage}
                    onChange={(e) => {
                      const v = Number.parseInt(e.target.value, 10);
                      setCurrentPage(Number.isFinite(v) ? v : referencePage);
                    }}
                    className="w-20 rounded-md border bg-background px-2 py-1 text-xs"
                  />
                  <span>/ {numPages ?? "…"}</span>
                  {showRefBoxes ? (
                    <span className="ml-2 rounded-md bg-muted px-2 py-1">
                      highlights on
                    </span>
                  ) : (
                    <span className="ml-2 rounded-md bg-muted px-2 py-1">
                      highlights off (not ref page)
                    </span>
                  )}
                </div>
              </div>

              <PdfViewer
                fileUrl={pdfUrl}
                pageNumber={safeCurrentPage}
                onNumPages={(n) => setNumPages(n)}
                boxes={showRefBoxes ? [...boxes] : []}
                showBoxes={showRefBoxes}
              />
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}