import { useRef, useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Pencil, Type, Upload, RotateCcw } from "lucide-react";

interface SignaturePadProps {
  onChange: (dataUrl: string | null, method: "draw" | "type" | "upload") => void;
  signerName?: string;
}

const SCRIPT_FONTS = [
  { label: "Allura", style: "'Allura', cursive" },
  { label: "Dancing Script", style: "'Dancing Script', cursive" },
  { label: "Great Vibes", style: "'Great Vibes', cursive" },
];

export default function SignaturePad({ onChange, signerName = "" }: SignaturePadProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [drawing, setDrawing] = useState(false);
  const [hasDrawn, setHasDrawn] = useState(false);
  const [typedName, setTypedName] = useState(signerName);
  const [fontIdx, setFontIdx] = useState(0);
  const [tab, setTab] = useState<"draw" | "type" | "upload">("draw");

  // Inject Google Fonts once
  useEffect(() => {
    const id = "avria-sig-fonts";
    if (document.getElementById(id)) return;
    const link = document.createElement("link");
    link.id = id;
    link.rel = "stylesheet";
    link.href = "https://fonts.googleapis.com/css2?family=Allura&family=Dancing+Script:wght@600&family=Great+Vibes&display=swap";
    document.head.appendChild(link);
  }, []);

  useEffect(() => { setTypedName(signerName); }, [signerName]);

  const getCtx = () => canvasRef.current?.getContext("2d");

  const start = (e: React.MouseEvent | React.TouchEvent) => {
    const ctx = getCtx(); if (!ctx) return;
    const { x, y } = getPos(e);
    ctx.beginPath(); ctx.moveTo(x, y); setDrawing(true);
  };
  const move = (e: React.MouseEvent | React.TouchEvent) => {
    if (!drawing) return;
    const ctx = getCtx(); if (!ctx) return;
    const { x, y } = getPos(e);
    ctx.lineTo(x, y); ctx.strokeStyle = "#0a2540"; ctx.lineWidth = 2; ctx.lineCap = "round"; ctx.stroke();
    setHasDrawn(true);
  };
  const end = () => {
    setDrawing(false);
    if (canvasRef.current && hasDrawn) onChange(canvasRef.current.toDataURL("image/png"), "draw");
  };

  const getPos = (e: React.MouseEvent | React.TouchEvent) => {
    const c = canvasRef.current!; const r = c.getBoundingClientRect();
    if ("touches" in e) {
      return { x: (e.touches[0].clientX - r.left) * (c.width / r.width), y: (e.touches[0].clientY - r.top) * (c.height / r.height) };
    }
    return { x: (e.clientX - r.left) * (c.width / r.width), y: (e.clientY - r.top) * (c.height / r.height) };
  };

  const clearCanvas = () => {
    const ctx = getCtx(); if (!ctx || !canvasRef.current) return;
    ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
    setHasDrawn(false); onChange(null, "draw");
  };

  const renderTyped = (name: string, fontStyle: string): string => {
    const c = document.createElement("canvas");
    c.width = 600; c.height = 160;
    const ctx = c.getContext("2d")!;
    ctx.fillStyle = "#0a2540";
    ctx.font = `64px ${fontStyle}`;
    ctx.textBaseline = "middle";
    ctx.fillText(name || " ", 20, 80);
    return c.toDataURL("image/png");
  };

  const onTypedChange = (name: string, idx: number) => {
    setTypedName(name); setFontIdx(idx);
    if (name.trim()) onChange(renderTyped(name, SCRIPT_FONTS[idx].style), "type");
    else onChange(null, "type");
  };

  const onUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0]; if (!f) return;
    const reader = new FileReader();
    reader.onload = () => onChange(reader.result as string, "upload");
    reader.readAsDataURL(f);
  };

  return (
    <div className="border rounded-lg p-4 bg-card">
      <Tabs value={tab} onValueChange={(v) => { setTab(v as any); onChange(null, v as any); clearCanvas(); }}>
        <TabsList className="grid grid-cols-3 w-full mb-3">
          <TabsTrigger value="draw"><Pencil className="h-3.5 w-3.5 mr-1" /> Draw</TabsTrigger>
          <TabsTrigger value="type"><Type className="h-3.5 w-3.5 mr-1" /> Type</TabsTrigger>
          <TabsTrigger value="upload"><Upload className="h-3.5 w-3.5 mr-1" /> Upload</TabsTrigger>
        </TabsList>

        <TabsContent value="draw">
          <div className="border-2 border-dashed border-border rounded bg-background">
            <canvas
              ref={canvasRef} width={600} height={200}
              className="w-full h-[200px] cursor-crosshair touch-none"
              onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
              onTouchStart={start} onTouchMove={move} onTouchEnd={end}
            />
          </div>
          <Button type="button" variant="ghost" size="sm" onClick={clearCanvas} className="mt-2 gap-1">
            <RotateCcw className="h-3.5 w-3.5" /> Clear
          </Button>
        </TabsContent>

        <TabsContent value="type" className="space-y-3">
          <div>
            <Label className="text-xs">Type your full name</Label>
            <Input value={typedName} onChange={e => onTypedChange(e.target.value, fontIdx)} placeholder="John Doe" />
          </div>
          <div>
            <Label className="text-xs">Style</Label>
            <div className="grid grid-cols-3 gap-2 mt-1">
              {SCRIPT_FONTS.map((f, i) => (
                <button key={f.label} type="button" onClick={() => onTypedChange(typedName, i)}
                  className={`border rounded p-3 text-2xl truncate ${fontIdx === i ? "border-primary bg-primary/5" : "border-border"}`}
                  style={{ fontFamily: f.style }}>
                  {typedName || "Signature"}
                </button>
              ))}
            </div>
          </div>
        </TabsContent>

        <TabsContent value="upload">
          <Input type="file" accept="image/png,image/jpeg" onChange={onUpload} />
          <p className="text-xs text-muted-foreground mt-2">Upload a transparent PNG of your signature for best results.</p>
        </TabsContent>
      </Tabs>
    </div>
  );
}
