import React, { useRef, useState, useEffect } from "react";
import type { SignaturePayload } from "../../types";

interface SignatureCaptureProps {
  onSave: (payload: SignaturePayload) => void;
  onCancel?: () => void;
}

export const SignatureCapture: React.FC<SignatureCaptureProps> = ({
  onSave,
  onCancel,
}) => {
  const [activeTab, setActiveTab] = useState<"draw" | "type" | "upload">(
    "draw",
  );
  const [typedName, setTypedName] = useState("");
  const [typedFont, setTypedFont] = useState<
    "font-serif" | "font-mono" | "font-sans-cursive"
  >("font-sans-cursive");
  const [uploadedImage, setUploadedImage] = useState<string | null>(null);

  // Canvas drawing state
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const lastPos = useRef({ x: 0, y: 0 });

  // Get canvas context and configure brush
  const getContext = (): CanvasRenderingContext2D | null => {
    if (!canvasRef.current) return null;
    const ctx = canvasRef.current.getContext("2d");
    if (ctx) {
      ctx.lineWidth = 2.5;
      ctx.lineCap = "round";
      ctx.strokeStyle = "#477A2B"; // primary-800 (green/ink accent, no black)
    }
    return ctx;
  };

  const getCoordinates = (e: React.MouseEvent | React.TouchEvent) => {
    if (!canvasRef.current) return { x: 0, y: 0 };
    const rect = canvasRef.current.getBoundingClientRect();

    // Check if it's a touch event
    if ("touches" in e) {
      if (e.touches.length === 0) return { x: 0, y: 0 };
      return {
        x: e.touches[0].clientX - rect.left,
        y: e.touches[0].clientY - rect.top,
      };
    } else {
      return {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top,
      };
    }
  };

  const startDrawing = (
    e:
      | React.MouseEvent<HTMLCanvasElement>
      | React.TouchEvent<HTMLCanvasElement>,
  ) => {
    e.preventDefault();
    const pos = getCoordinates(e);
    lastPos.current = pos;
    setIsDrawing(true);
  };

  const draw = (
    e:
      | React.MouseEvent<HTMLCanvasElement>
      | React.TouchEvent<HTMLCanvasElement>,
  ) => {
    if (!isDrawing) return;
    e.preventDefault();
    const ctx = getContext();
    if (!ctx) return;

    const pos = getCoordinates(e);
    ctx.beginPath();
    ctx.moveTo(lastPos.current.x, lastPos.current.y);
    ctx.lineTo(pos.x, pos.y);
    ctx.stroke();
    lastPos.current = pos;
  };

  const stopDrawing = () => {
    setIsDrawing(false);
  };

  const clearCanvas = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (ctx) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
  };

  // Resize canvas handler
  useEffect(() => {
    if (canvasRef.current && activeTab === "draw") {
      const canvas = canvasRef.current;
      canvas.width = canvas.parentElement?.clientWidth || 500;
      canvas.height = 180;
      clearCanvas();
    }
  }, [activeTab]);

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        if (event.target?.result) {
          setUploadedImage(event.target.result as string);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  const handleSubmit = () => {
    if (activeTab === "draw") {
      if (!canvasRef.current) return;
      // Convert canvas to image
      const dataUrl = canvasRef.current.toDataURL("image/png");
      onSave({ type: "draw", dataUrl });
    } else if (activeTab === "type") {
      if (!typedName.trim()) return;

      // Render typed text to a canvas to extract as image
      const tempCanvas = document.createElement("canvas");
      tempCanvas.width = 400;
      tempCanvas.height = 100;
      const ctx = tempCanvas.getContext("2d");
      if (ctx) {
        ctx.fillStyle = "#F7F9F6"; // light bg
        ctx.fillRect(0, 0, 400, 100);

        // Match fonts
        let fontStyle = "italic 32px Georgia";
        if (typedFont === "font-mono") fontStyle = "italic 32px Courier New";
        if (typedFont === "font-sans-cursive")
          fontStyle = 'italic 32px "Lucida Handwriting", cursive, sans-serif';

        ctx.font = fontStyle;
        ctx.fillStyle = "#477A2B"; // green ink, no black
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        ctx.fillText(typedName, 200, 50);
      }
      onSave({ type: "type", dataUrl: tempCanvas.toDataURL("image/png") });
    } else if (activeTab === "upload") {
      if (!uploadedImage) return;
      onSave({ type: "upload", dataUrl: uploadedImage });
    }
  };

  return (
    <div className="w-full rounded-xl border border-ink-100 bg-white p-6 shadow-premium transition-premium">
      {/* Tabs */}
      <div className="mb-6 flex border-b border-ink-100 pb-2">
        <button
          type="button"
          onClick={() => setActiveTab("draw")}
          className={`mr-4 pb-2 text-sm font-semibold transition-colors ${
            activeTab === "draw"
              ? "border-b-2 border-primary-500 text-ink-800"
              : "text-ink-600 hover:text-ink-800"
          }`}
        >
          Draw Signature
        </button>
        <button
          type="button"
          onClick={() => setActiveTab("type")}
          className={`mr-4 pb-2 text-sm font-semibold transition-colors ${
            activeTab === "type"
              ? "border-b-2 border-primary-500 text-ink-800"
              : "text-ink-600 hover:text-ink-800"
          }`}
        >
          Type Signature
        </button>
        <button
          type="button"
          onClick={() => setActiveTab("upload")}
          className={`pb-2 text-sm font-semibold transition-colors ${
            activeTab === "upload"
              ? "border-b-2 border-primary-500 text-ink-800"
              : "text-ink-600 hover:text-ink-800"
          }`}
        >
          Upload Image
        </button>
      </div>

      {/* Drawing Area */}
      {activeTab === "draw" && (
        <div>
          <div className="relative mb-3 rounded-lg border border-dashed border-ink-300 bg-ink-50">
            <canvas
              ref={canvasRef}
              onMouseDown={startDrawing}
              onMouseMove={draw}
              onMouseUp={stopDrawing}
              onMouseLeave={stopDrawing}
              onTouchStart={startDrawing}
              onTouchMove={draw}
              onTouchEnd={stopDrawing}
              className="block cursor-crosshair rounded-lg"
            />
            <button
              type="button"
              onClick={clearCanvas}
              className="absolute right-3 top-3 rounded bg-white px-2.5 py-1 text-xs font-semibold text-ink-600 shadow border border-ink-100 hover:bg-ink-50"
            >
              Clear
            </button>
          </div>
          <p className="text-xs text-ink-600">
            Use your mouse or touchscreen to sign in the box above.
          </p>
        </div>
      )}

      {/* Typing Area */}
      {activeTab === "type" && (
        <div>
          <div className="mb-4">
            <label className="block text-xs font-semibold text-ink-600 mb-1.5">
              Enter Your Full Name
            </label>
            <input
              type="text"
              value={typedName}
              onChange={(e) => setTypedName(e.target.value)}
              placeholder="e.g. John Doe"
              className="w-full rounded-lg border border-ink-200 px-3.5 py-2 text-sm focus:border-primary-500 focus:outline-none"
            />
          </div>
          <div className="mb-4 flex gap-3">
            <button
              type="button"
              onClick={() => setTypedFont("font-sans-cursive")}
              className={`rounded-lg border px-3 py-2 text-sm font-medium transition-all ${
                typedFont === "font-sans-cursive"
                  ? "border-primary-500 bg-primary-50"
                  : "border-ink-100 bg-white hover:bg-ink-50"
              }`}
              style={{
                fontFamily: '"Lucida Handwriting", cursive, sans-serif',
              }}
            >
              Signature Style 1
            </button>
            <button
              type="button"
              onClick={() => setTypedFont("font-serif")}
              className={`rounded-lg border px-3 py-2 text-sm font-serif italic transition-all ${
                typedFont === "font-serif"
                  ? "border-primary-500 bg-primary-50"
                  : "border-ink-100 bg-white hover:bg-ink-50"
              }`}
            >
              Signature Style 2
            </button>
            <button
              type="button"
              onClick={() => setTypedFont("font-mono")}
              className={`rounded-lg border px-3 py-2 text-sm font-mono italic transition-all ${
                typedFont === "font-mono"
                  ? "border-primary-500 bg-primary-50"
                  : "border-ink-100 bg-white hover:bg-ink-50"
              }`}
            >
              Signature Style 3
            </button>
          </div>
          <div className="rounded-lg border border-ink-100 bg-ink-50 py-6 text-center shadow-inner">
            {typedName ? (
              <span
                className={`text-2xl text-primary-800 ${
                  typedFont === "font-sans-cursive"
                    ? "font-sans" // Fallback handled inline
                    : typedFont
                }`}
                style={
                  typedFont === "font-sans-cursive"
                    ? {
                        fontFamily:
                          '"Lucida Handwriting", cursive, Georgia, serif',
                        fontStyle: "italic",
                      }
                    : { fontStyle: "italic" }
                }
              >
                {typedName}
              </span>
            ) : (
              <span className="text-sm italic text-ink-300">
                Your Signature Preview
              </span>
            )}
          </div>
        </div>
      )}

      {/* Uploading Area */}
      {activeTab === "upload" && (
        <div>
          <div className="flex items-center justify-center w-full">
            <label className="flex flex-col items-center justify-center w-full h-36 border-2 border-ink-300 border-dashed rounded-lg cursor-pointer bg-ink-50 hover:bg-white transition-colors">
              <div className="flex flex-col items-center justify-center pt-5 pb-6">
                <svg
                  className="w-8 h-8 mb-3 text-ink-600"
                  aria-hidden="true"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 20 16"
                >
                  <path
                    stroke="currentColor"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth="2"
                    d="M13 13h3a3 3 0 0 0 0-6h-.025A5.56 5.56 0 0 0 16 6.5 5.5 5.5 0 0 0 5.207 5.021C5.137 5.017 5.071 5 5 5a4 4 0 0 0 0 8h2.167M10 15V6m0 0L8 8m2-2 2 2"
                  />
                </svg>
                <p className="mb-2 text-sm text-ink-600">
                  <span className="font-semibold">Click to upload</span>{" "}
                  signature image
                </p>
                <p className="text-xs text-ink-600">PNG or JPG (Max 500KB)</p>
              </div>
              <input
                type="file"
                className="hidden"
                accept="image/*"
                onChange={handleFileUpload}
              />
            </label>
          </div>
          {uploadedImage && (
            <div className="mt-4 flex flex-col items-center">
              <p className="text-xs font-semibold text-ink-600 mb-1">
                Uploaded Signature Preview:
              </p>
              <img
                src={uploadedImage}
                alt="Signature Upload"
                className="max-h-24 object-contain rounded border border-ink-100 bg-white p-2"
              />
            </div>
          )}
        </div>
      )}

      {/* Action buttons */}
      <div className="mt-6 flex justify-end gap-3">
        {onCancel && (
          <button
            type="button"
            onClick={onCancel}
            className="rounded-lg border border-ink-200 bg-white px-4 py-2 text-sm font-semibold text-ink-600 hover:bg-ink-50 transition-premium"
          >
            Cancel
          </button>
        )}
        <button
          type="button"
          onClick={handleSubmit}
          disabled={
            activeTab === "draw" || // Canvas validation handled at submit
            (activeTab === "type" && !typedName.trim()) ||
            (activeTab === "upload" && !uploadedImage)
          }
          className="rounded-lg bg-primary-400 px-5 py-2 text-sm font-semibold text-ink-800 hover:bg-primary-300 disabled:opacity-50 disabled:cursor-not-allowed transition-premium shadow-premium"
        >
          Sign Document
        </button>
      </div>
    </div>
  );
};
