"use client";

import { useState, useRef, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { cn } from "@/lib/utils";
import { Trash2, Pencil } from "lucide-react";

export interface Annotation {
  id: string;
  x: number;       // % of image width
  y: number;       // % of image height
  width: number;   // % of image width
  height: number;  // % of image height
  label: string;
  colorIndex: number;
}

interface ImageAnnotatorProps {
  imageUrl: string;
  value?: Annotation[];
  onChange?: (annotations: Annotation[]) => void;
  readOnly?: boolean;
}

// Each slot: border color, fill, swatch bg, label pill bg
const ANN_STYLES = [
  { box: "border-red-500 bg-red-500/10",    swatch: "bg-red-500",    pill: "bg-red-500"    },
  { box: "border-orange-500 bg-orange-500/10", swatch: "bg-orange-500", pill: "bg-orange-500" },
  { box: "border-yellow-400 bg-yellow-400/10", swatch: "bg-yellow-400", pill: "bg-yellow-400" },
  { box: "border-green-500 bg-green-500/10",   swatch: "bg-green-500",  pill: "bg-green-500"  },
  { box: "border-blue-500 bg-blue-500/10",     swatch: "bg-blue-500",   pill: "bg-blue-500"   },
  { box: "border-violet-500 bg-violet-500/10", swatch: "bg-violet-500", pill: "bg-violet-500" },
  { box: "border-pink-500 bg-pink-500/10",     swatch: "bg-pink-500",   pill: "bg-pink-500"   },
] as const;

function toPercent(r: DOMRect, clientX: number, clientY: number) {
  return {
    x: Math.max(0, Math.min(100, ((clientX - r.left) / r.width) * 100)),
    y: Math.max(0, Math.min(100, ((clientY - r.top) / r.height) * 100)),
  };
}

type DraftRect = Omit<Annotation, "id" | "label">;

/** Applies dynamic % position/size imperatively so the `style` JSX prop is never needed. */
function PositionedBox({
  x, y, width, height, className, children,
}: { x: number; y: number; width: number; height: number; className?: string; children?: React.ReactNode }) {
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    el.style.left = `${x}%`;
    el.style.top = `${y}%`;
    el.style.width = `${width}%`;
    el.style.height = `${height}%`;
  }, [x, y, width, height]);
  return <div ref={ref} className={cn("absolute", className)}>{children}</div>;
}

export function ImageAnnotator({
  imageUrl,
  value = [],
  onChange,
  readOnly = false,
}: ImageAnnotatorProps) {
  const [annotations, setAnnotations] = useState<Annotation[]>(value);
  const [isDrawing, setIsDrawing] = useState(false);
  const [startPos, setStartPos] = useState({ x: 0, y: 0 });
  const [draft, setDraft] = useState<DraftRect | null>(null);
  const [colorIndex, setColorIndex] = useState(0);
  const containerRef = useRef<HTMLDivElement>(null);

  const commit = (next: Annotation[]) => {
    setAnnotations(next);
    onChange?.(next);
  };

  const getXY = (e: React.MouseEvent | React.TouchEvent) => {
    if ("touches" in e) {
      const t = e.touches[0] ?? e.changedTouches[0];
      return { clientX: t.clientX, clientY: t.clientY };
    }
    return { clientX: e.clientX, clientY: e.clientY };
  };

  const posFromEvent = (e: React.MouseEvent | React.TouchEvent) => {
    if (!containerRef.current) return { x: 0, y: 0 };
    const { clientX, clientY } = getXY(e);
    return toPercent(containerRef.current.getBoundingClientRect(), clientX, clientY);
  };

  const makeDraft = (start: { x: number; y: number }, end: { x: number; y: number }): DraftRect => ({
    x: Math.min(start.x, end.x),
    y: Math.min(start.y, end.y),
    width: Math.abs(end.x - start.x),
    height: Math.abs(end.y - start.y),
    colorIndex: colorIndex % ANN_STYLES.length,
  });

  const finalise = (d: DraftRect) => {
    if (d.width > 1.5 && d.height > 1.5) {
      const ann: Annotation = { ...d, id: Date.now().toString(), label: `Region ${annotations.length + 1}` };
      commit([...annotations, ann]);
      setColorIndex((c) => c + 1);
    }
    setIsDrawing(false);
    setDraft(null);
  };

  const onMouseDown = (e: React.MouseEvent) => {
    if (readOnly) return;
    e.preventDefault();
    setStartPos(posFromEvent(e));
    setIsDrawing(true);
  };

  const onMouseMove = (e: React.MouseEvent) => {
    if (!isDrawing) return;
    setDraft(makeDraft(startPos, posFromEvent(e)));
  };

  const onMouseUp = (e: React.MouseEvent) => {
    if (!isDrawing) return;
    finalise(makeDraft(startPos, posFromEvent(e)));
  };

  const onTouchStart = (e: React.TouchEvent) => {
    if (readOnly) return;
    e.preventDefault();
    setStartPos(posFromEvent(e));
    setIsDrawing(true);
  };

  const onTouchMove = (e: React.TouchEvent) => {
    if (!isDrawing) return;
    e.preventDefault();
    setDraft(makeDraft(startPos, posFromEvent(e)));
  };

  const onTouchEnd = (e: React.TouchEvent) => {
    if (!isDrawing) return;
    const touch = e.changedTouches[0];
    if (!touch || !containerRef.current) return;
    const end = toPercent(containerRef.current.getBoundingClientRect(), touch.clientX, touch.clientY);
    finalise(makeDraft(startPos, end));
  };

    // Nothing here — position applied imperatively in PositionedBox to avoid style prop warnings

  return (
    <div className="space-y-3">
      {!readOnly && (
        <p className="text-xs text-muted-foreground flex items-center gap-1.5">
          <Pencil className="h-3 w-3" />
          {typeof window !== "undefined" && "ontouchstart" in window
            ? "Tap and drag on the image to mark regions"
            : "Click and drag on the image to mark regions of interest"}
        </p>
      )}

      {/* Image + overlay */}
      <div
        ref={containerRef}
        className={cn(
          "relative select-none overflow-hidden rounded-xl border-2 border-border touch-none",
          !readOnly && "cursor-crosshair",
        )}
        onMouseDown={onMouseDown}
        onMouseMove={onMouseMove}
        onMouseUp={onMouseUp}
        onMouseLeave={() => { setIsDrawing(false); setDraft(null); }}
        onTouchStart={onTouchStart}
        onTouchMove={onTouchMove}
        onTouchEnd={onTouchEnd}
      >
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={imageUrl}
          alt="Annotate this image"
          className="w-full h-auto block pointer-events-none"
          draggable={false}
        />

        {/* Committed annotations */}
        {annotations.map((ann) => {
          const s = ANN_STYLES[ann.colorIndex % ANN_STYLES.length];
          return (
            <PositionedBox key={ann.id} x={ann.x} y={ann.y} width={ann.width} height={ann.height}
              className={cn("border-2 rounded pointer-events-none", s.box)}
            >
              <span className={cn("absolute -top-5 left-0 text-[10px] font-bold px-1.5 py-0.5 rounded text-white whitespace-nowrap max-w-[120px] truncate", s.pill)}>
                {ann.label}
              </span>
            </PositionedBox>
          );
        })}

        {/* Draft rectangle while drawing */}
        {draft && (
          <PositionedBox x={draft.x} y={draft.y} width={draft.width} height={draft.height}
            className={cn("border-2 rounded pointer-events-none", ANN_STYLES[draft.colorIndex % ANN_STYLES.length].box)}
          />
        )}

        {!readOnly && annotations.length === 0 && !isDrawing && (
          <div className="absolute inset-0 flex items-end justify-center pb-4 pointer-events-none">
            <span className="text-xs text-white bg-black/50 backdrop-blur-sm px-3 py-1.5 rounded-full">
              Drag to annotate
            </span>
          </div>
        )}
      </div>

      {/* Label list */}
      <AnimatePresence initial={false}>
        {annotations.map((ann, i) => {
          const s = ANN_STYLES[ann.colorIndex % ANN_STYLES.length];
          return (
            <motion.div
              key={ann.id}
              initial={{ opacity: 0, y: -4 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -4 }}
              transition={{ duration: 0.15 }}
              className="flex items-center gap-2"
            >
              <div className={cn("h-3 w-3 rounded shrink-0", s.swatch)} />
              <input
                type="text"
                value={ann.label}
                onChange={(e) => commit(annotations.map((a) => a.id === ann.id ? { ...a, label: e.target.value } : a))}
                aria-label={`Label for annotation ${i + 1}`}
                className="flex-1 bg-muted/50 border border-border/50 rounded-lg px-2.5 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-primary"
                placeholder={`Label region ${i + 1}...`}
                readOnly={readOnly}
              />
              {!readOnly && (
                <button
                  type="button"
                  onClick={() => commit(annotations.filter((a) => a.id !== ann.id))}
                  aria-label="Remove annotation"
                  className="text-muted-foreground hover:text-red-400 transition-colors"
                >
                  <Trash2 className="h-3.5 w-3.5" />
                </button>
              )}
            </motion.div>
          );
        })}
      </AnimatePresence>

      {annotations.length > 0 && (
        <p className="text-xs text-muted-foreground">
          {annotations.length} annotation{annotations.length !== 1 ? "s" : ""}
          {!readOnly && " — click labels to rename"}
        </p>
      )}
    </div>
  );
}
