"use client";

import { useEffect, useRef, useState } from "react";
import { drawAnnotationsOnCanvas } from "@/lib/annotations";
import { setupHiDpiCanvas } from "@/lib/canvas";
import type { Annotation, AnnotationTool, Screenshot } from "@/lib/types";

const COLORS = ["#e11d48", "#2563eb", "#0d9488", "#ca8a04", "#7c3aed"];

interface Props {
  screenshot: Screenshot;
  onChange: (annotations: Annotation[]) => void;
}

export function AnnotationEditor({ screenshot, onChange }: Props) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const imageRef = useRef<HTMLImageElement | null>(null);
  const [tool, setTool] = useState<AnnotationTool>("arrow");
  const [color, setColor] = useState(COLORS[0]);
  const [draft, setDraft] = useState<Annotation | null>(null);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const drawing = useRef(false);

  const annotations = screenshot.annotations;

  useEffect(() => {
    const img = new Image();
    img.src = `/api/uploads/${screenshot.id}`;
    img.onload = () => {
      imageRef.current = img;
      redraw(annotations, null);
    };
  }, [screenshot.id]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    redraw(annotations, draft);
  }, [annotations, draft, selectedId]); // eslint-disable-line react-hooks/exhaustive-deps

  function redraw(anns: Annotation[], current: Annotation | null) {
    const canvas = canvasRef.current;
    const img = imageRef.current;
    if (!canvas || !img) return;

    const maxW = canvas.parentElement?.clientWidth || 800;
    const scale = Math.min(1, maxW / img.naturalWidth);
    const w = Math.round(img.naturalWidth * scale);
    const h = Math.round(img.naturalHeight * scale);
    const setup = setupHiDpiCanvas(canvas, w, h);
    if (!setup) return;

    const { ctx, width, height } = setup;
    ctx.clearRect(0, 0, width, height);
    ctx.drawImage(img, 0, 0, width, height);
    drawAnnotationsOnCanvas(ctx, anns, width, height);
    if (current) drawAnnotationsOnCanvas(ctx, [current], width, height);

    if (selectedId) {
      const selected = anns.find((a) => a.id === selectedId);
      if (selected) {
        ctx.save();
        ctx.strokeStyle = "#0f172a";
        ctx.setLineDash([4, 4]);
        ctx.lineWidth = 1;
        const x1 = selected.x1 * width;
        const y1 = selected.y1 * height;
        const x2 = selected.x2 * width;
        const y2 = selected.y2 * height;
        ctx.strokeRect(
          Math.min(x1, x2) - 4,
          Math.min(y1, y2) - 4,
          Math.abs(x2 - x1) + 8,
          Math.abs(y2 - y1) + 8
        );
        ctx.restore();
      }
    }
  }

  function pointerPos(e: React.PointerEvent<HTMLCanvasElement>) {
    const canvas = canvasRef.current!;
    const rect = canvas.getBoundingClientRect();
    return {
      x: (e.clientX - rect.left) / rect.width,
      y: (e.clientY - rect.top) / rect.height,
    };
  }

  function onPointerDown(e: React.PointerEvent<HTMLCanvasElement>) {
    e.currentTarget.setPointerCapture(e.pointerId);
    drawing.current = true;
    const p = pointerPos(e);
    setSelectedId(null);
    setDraft({
      id: crypto.randomUUID(),
      type: tool,
      color,
      strokeWidth: 3,
      x1: p.x,
      y1: p.y,
      x2: p.x,
      y2: p.y,
    });
  }

  function onPointerMove(e: React.PointerEvent<HTMLCanvasElement>) {
    if (!drawing.current || !draft) return;
    const p = pointerPos(e);
    setDraft({ ...draft, x2: p.x, y2: p.y });
  }

  function onPointerUp() {
    if (!drawing.current || !draft) return;
    drawing.current = false;
    const dx = Math.abs(draft.x2 - draft.x1);
    const dy = Math.abs(draft.y2 - draft.y1);
    if (dx > 0.01 || dy > 0.01) {
      onChange([...annotations, draft]);
      setSelectedId(draft.id);
    }
    setDraft(null);
  }

  function removeSelected() {
    if (!selectedId) return;
    onChange(annotations.filter((a) => a.id !== selectedId));
    setSelectedId(null);
  }

  function clearAll() {
    onChange([]);
    setSelectedId(null);
  }

  return (
    <div className="space-y-3">
      <div className="flex flex-wrap items-center gap-2">
        {(
          [
            ["arrow", "Arrow"],
            ["rectangle", "Rectangle"],
            ["circle", "Circle"],
          ] as const
        ).map(([value, label]) => (
          <button
            key={value}
            type="button"
            onClick={() => setTool(value)}
            className={`rounded-md px-3 py-1.5 text-sm ${
              tool === value
                ? "bg-[var(--ink)] text-white"
                : "bg-[var(--wash)] text-[var(--ink)]"
            }`}
          >
            {label}
          </button>
        ))}
        <div className="mx-1 h-5 w-px bg-[var(--line)]" />
        {COLORS.map((c) => (
          <button
            key={c}
            type="button"
            aria-label={`Color ${c}`}
            onClick={() => setColor(c)}
            className={`h-6 w-6 rounded-full border-2 ${
              color === c ? "border-[var(--ink)]" : "border-transparent"
            }`}
            style={{ background: c }}
          />
        ))}
        <div className="ml-auto flex gap-2">
          <button
            type="button"
            onClick={removeSelected}
            disabled={!selectedId}
            className="rounded-md px-3 py-1.5 text-sm text-[var(--muted)] disabled:opacity-40"
          >
            Delete selected
          </button>
          <button
            type="button"
            onClick={clearAll}
            className="rounded-md px-3 py-1.5 text-sm text-[var(--danger)]"
          >
            Clear all
          </button>
        </div>
      </div>
      <div className="overflow-hidden rounded-xl border border-[var(--line)] bg-white">
        <canvas
          ref={canvasRef}
          className="block max-w-full cursor-crosshair touch-none"
          onPointerDown={onPointerDown}
          onPointerMove={onPointerMove}
          onPointerUp={onPointerUp}
          onPointerCancel={onPointerUp}
        />
      </div>
      <p className="text-xs text-[var(--muted)]">
        Draw on the screenshot. Annotations are saved with the feature and
        appear in the PDF.
      </p>
    </div>
  );
}
