import React, { useEffect, useMemo, useRef, useState } from "react";

export type Point = { x: number; y: number };
export type LandmarkKey =
  | "pelvis_mid"
  | "t1_center"
  | "tp_point"
  | "csl_p1"
  | "csl_p2";

const LANDMARK_ORDER: Array<{ key: LandmarkKey; label: string }> = [
  { key: "pelvis_mid", label: "Pelvis Mid" },
  { key: "t1_center", label: "T1 Center" },
  { key: "tp_point", label: "Thoracic Prominence (TP)" },
  { key: "csl_p1", label: "CSL Point 1 (top)" },
  { key: "csl_p2", label: "CSL Point 2 (bottom)" },
];

export function LandmarkCanvas({
  imageUrl,
  onChange,
  initialLandmarks,
}: {
  imageUrl?: string;
  onChange: (landmarks: Record<string, Point>, completed: boolean) => void;
  initialLandmarks?: Record<string, Point>;
}) {
  const imgRef = useRef<HTMLImageElement | null>(null);

  const [landmarks, setLandmarks] = useState<Record<string, Point>>({});
  const [activeIndex, setActiveIndex] = useState(0);

  const active = LANDMARK_ORDER[activeIndex];

  const completed = useMemo(
    () => LANDMARK_ORDER.every((l) => Boolean(landmarks[l.key])),
    [landmarks]
  );

  useEffect(() => {
    onChange(landmarks, completed);
  }, [landmarks, completed, onChange]);

  useEffect(() => {
    if (initialLandmarks && Object.keys(initialLandmarks).length) {
      setLandmarks(initialLandmarks);
    }
  }, [initialLandmarks]);

  function reset() {
    setLandmarks({});
    setActiveIndex(0);
  }

  function handleClick(e: React.MouseEvent) {
    if (!imgRef.current) return;

    const rect = imgRef.current.getBoundingClientRect();
    const x = Math.round(e.clientX - rect.left);
    const y = Math.round(e.clientY - rect.top);

    const next = { ...landmarks, [active.key]: { x, y } };
    setLandmarks(next);

    if (activeIndex < LANDMARK_ORDER.length - 1) {
      setActiveIndex(activeIndex + 1);
    }
  }

  return (
    <div className="landmark-layout">
      <div className="panel">
        <h3>Landmarks</h3>

        <ol className="list">
          {LANDMARK_ORDER.map((l, idx) => (
            <li key={l.key} className={idx === activeIndex ? "active" : ""}>
              <div className="label">{l.label}</div>
              <div className="meta">
                {landmarks[l.key]
                  ? `x=${landmarks[l.key].x}, y=${landmarks[l.key].y}`
                  : "pending"}
              </div>
            </li>
          ))}
        </ol>

        <div className="row gap">
          <button className="btn secondary" onClick={reset}>
            Reset
          </button>
          <div className="pill">
            {completed ? "Ready to submit" : `Next: ${active.label}`}
          </div>
        </div>
      </div>

      <div className="canvasWrap">
        <div className="imgWrap fixed-250" onClick={handleClick}>
          <img
            ref={imgRef}
            src={imageUrl}
            className="xray"
            alt="AP X-ray"
            draggable={false}
          />

          <svg className="overlay">
            {landmarks["csl_p1"] && landmarks["csl_p2"] && (
              <line
                x1={landmarks["csl_p1"].x}
                y1={landmarks["csl_p1"].y}
                x2={landmarks["csl_p2"].x}
                y2={landmarks["csl_p2"].y}
                stroke="white"
                strokeWidth="2"
                strokeDasharray="6 6"
              />
            )}

            {Object.entries(landmarks).map(([k, p]) => (
              <g key={k}>
                <circle cx={p.x} cy={p.y} r="6" fill="white" />
                <circle cx={p.x} cy={p.y} r="3" fill="black" />
              </g>
            ))}
          </svg>
        </div>

        <div className="hint">Click to place the active landmark.</div>
      </div>
    </div>
  );
}
