import { useEffect, useRef, useState } from "react";
import { Document, Page, pdfjs } from "react-pdf";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ChevronLeft, ChevronRight, X, Pen, Calendar as CalIcon, User as UserIcon } from "lucide-react";
import { cn } from "@/lib/utils";

// Use the bundled worker
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  "pdfjs-dist/build/pdf.worker.min.mjs",
  import.meta.url
).toString();

export interface PlacedField {
  id: string;
  recipientIndex: number;
  field_type: "signature" | "date" | "name";
  page_number: number;
  x_ratio: number;
  y_ratio: number;
  width_ratio: number;
  height_ratio: number;
}

interface Props {
  fileUrl: string;
  recipients: { name: string; email: string }[];
  fields: PlacedField[];
  onChange: (fields: PlacedField[]) => void;
}

const FIELD_COLORS = [
  "border-primary bg-primary/15 text-primary",
  "border-emerald-500 bg-emerald-500/15 text-emerald-700",
  "border-amber-500 bg-amber-500/15 text-amber-700",
  "border-rose-500 bg-rose-500/15 text-rose-700",
];

const FIELD_DEFAULTS = {
  signature: { width_ratio: 0.22, height_ratio: 0.05 },
  date: { width_ratio: 0.14, height_ratio: 0.035 },
  name: { width_ratio: 0.22, height_ratio: 0.035 },
};

export default function SignatureFieldPlacer({ fileUrl, recipients, fields, onChange }: Props) {
  const [numPages, setNumPages] = useState(0);
  const [page, setPage] = useState(1);
  const [pageWidth, setPageWidth] = useState(700);
  const [activeRecipient, setActiveRecipient] = useState(0);
  const [activeType, setActiveType] = useState<"signature" | "date" | "name">("signature");
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const update = () => {
      if (containerRef.current) {
        setPageWidth(Math.min(containerRef.current.clientWidth - 24, 900));
      }
    };
    update();
    window.addEventListener("resize", update);
    return () => window.removeEventListener("resize", update);
  }, []);

  const handlePageClick = (e: React.MouseEvent<HTMLDivElement>) => {
    const target = e.currentTarget;
    const rect = target.getBoundingClientRect();
    const x_ratio = (e.clientX - rect.left) / rect.width;
    const y_ratio = (e.clientY - rect.top) / rect.height;
    const def = FIELD_DEFAULTS[activeType];
    const newField: PlacedField = {
      id: crypto.randomUUID(),
      recipientIndex: activeRecipient,
      field_type: activeType,
      page_number: page,
      x_ratio: Math.max(0, x_ratio - def.width_ratio / 2),
      y_ratio: Math.max(0, y_ratio - def.height_ratio / 2),
      width_ratio: def.width_ratio,
      height_ratio: def.height_ratio,
    };
    onChange([...fields, newField]);
  };

  const removeField = (id: string) => onChange(fields.filter(f => f.id !== id));

  const pageFields = fields.filter(f => f.page_number === page);

  return (
    <div className="border rounded-lg bg-muted/30">
      {/* Toolbar */}
      <div className="flex flex-wrap items-center gap-2 p-2 border-b bg-background rounded-t-lg">
        <div className="flex items-center gap-1">
          <Button type="button" variant="ghost" size="icon" className="h-7 w-7" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <span className="text-xs font-medium">Page {page} / {numPages || "…"}</span>
          <Button type="button" variant="ghost" size="icon" className="h-7 w-7" disabled={page >= numPages} onClick={() => setPage(p => p + 1)}>
            <ChevronRight className="h-4 w-4" />
          </Button>
        </div>

        <div className="h-5 w-px bg-border mx-1" />

        <Select value={String(activeRecipient)} onValueChange={v => setActiveRecipient(Number(v))}>
          <SelectTrigger className="h-7 w-[180px] text-xs"><SelectValue /></SelectTrigger>
          <SelectContent>
            {recipients.map((r, i) => (
              <SelectItem key={i} value={String(i)}>
                <span className={cn("inline-block h-2 w-2 rounded-full mr-2", FIELD_COLORS[i % 4].split(" ")[1])} />
                {r.name || r.email || `Signer ${i + 1}`}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <div className="flex items-center gap-1 ml-auto">
          {[
            { v: "signature" as const, label: "Signature", Icon: Pen },
            { v: "date" as const, label: "Date", Icon: CalIcon },
            { v: "name" as const, label: "Name", Icon: UserIcon },
          ].map(({ v, label, Icon }) => (
            <Button
              key={v} type="button" size="sm" variant={activeType === v ? "default" : "outline"}
              className="h-7 text-xs gap-1"
              onClick={() => setActiveType(v)}
            >
              <Icon className="h-3 w-3" /> {label}
            </Button>
          ))}
        </div>
      </div>

      <p className="text-[11px] text-muted-foreground px-3 py-1.5 border-b bg-background/50">
        Click on the document to place a {activeType} field for the selected signer.
      </p>

      {/* PDF + overlay */}
      <div ref={containerRef} className="overflow-auto max-h-[60vh] p-3 flex justify-center">
        <Document
          file={fileUrl}
          onLoadSuccess={({ numPages }) => setNumPages(numPages)}
          loading={<div className="p-12 text-sm text-muted-foreground">Loading document…</div>}
          error={<div className="p-12 text-sm text-destructive">Could not preview document. Fields can still be placed by page.</div>}
        >
          <div className="relative inline-block shadow-md" onClick={handlePageClick}>
            <Page pageNumber={page} width={pageWidth} renderTextLayer={false} renderAnnotationLayer={false} />
            {pageFields.map(f => (
              <div
                key={f.id}
                onClick={(e) => e.stopPropagation()}
                className={cn(
                  "absolute border-2 border-dashed rounded flex items-center justify-center text-[10px] font-semibold uppercase tracking-wide cursor-default group",
                  FIELD_COLORS[f.recipientIndex % 4]
                )}
                style={{
                  left: `${f.x_ratio * 100}%`,
                  top: `${f.y_ratio * 100}%`,
                  width: `${f.width_ratio * 100}%`,
                  height: `${f.height_ratio * 100}%`,
                }}
              >
                <span>{f.field_type}</span>
                <button
                  type="button"
                  onClick={() => removeField(f.id)}
                  className="absolute -top-2 -right-2 h-4 w-4 rounded-full bg-destructive text-destructive-foreground text-[9px] flex items-center justify-center opacity-0 group-hover:opacity-100"
                >
                  <X className="h-2.5 w-2.5" />
                </button>
              </div>
            ))}
          </div>
        </Document>
      </div>

      <div className="flex items-center justify-between p-2 border-t bg-background rounded-b-lg">
        <div className="flex flex-wrap gap-1">
          {recipients.map((r, i) => {
            const count = fields.filter(f => f.recipientIndex === i).length;
            return (
              <Badge key={i} variant="outline" className={cn("text-[10px]", FIELD_COLORS[i % 4])}>
                {r.name || `Signer ${i + 1}`}: {count}
              </Badge>
            );
          })}
        </div>
        {fields.length > 0 && (
          <Button type="button" variant="ghost" size="sm" className="h-7 text-xs" onClick={() => onChange([])}>
            Clear all
          </Button>
        )}
      </div>
    </div>
  );
}
