import { useState, useEffect, useRef } from 'react';
import { Loader2, ZoomIn, ZoomOut, RotateCw } from 'lucide-react';

const ZOOM_STEPS = [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 5];
const MIN_ZOOM = ZOOM_STEPS[0]!;
const MAX_ZOOM = ZOOM_STEPS[ZOOM_STEPS.length - 1]!;

type ImageRendererProps = {
  src: string;
  fileName: string;
};

export const ImageRenderer = ({ src, fileName }: ImageRendererProps) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [zoom, setZoom] = useState(1);
  const [rotation, setRotation] = useState(0);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState(false);
  const [dragging, setDragging] = useState(false);
  const [offset, setOffset] = useState({ x: 0, y: 0 });
  const dragStart = useRef({ x: 0, y: 0, ox: 0, oy: 0 });

  const zoomIn = () => {
    setZoom((z) => {
      const next = ZOOM_STEPS.find((s) => s > z);
      return next ?? z;
    });
  };

  const zoomOut = () => {
    setZoom((z) => {
      const prev = [...ZOOM_STEPS].reverse().find((s) => s < z);
      return prev ?? z;
    });
  };

  const resetView = () => {
    setZoom(1);
    setRotation(0);
    setOffset({ x: 0, y: 0 });
  };

  const rotate = () => {
    setRotation((r) => (r + 90) % 360);
  };

  const onWheel = (ev: React.WheelEvent) => {
    ev.preventDefault();
    if (ev.deltaY < 0) zoomIn();
    else zoomOut();
  };

  const onMouseDown = (ev: React.MouseEvent) => {
    if (zoom <= 1) return;
    ev.preventDefault();
    setDragging(true);
    dragStart.current = { x: ev.clientX, y: ev.clientY, ox: offset.x, oy: offset.y };

    const onMove = (e: MouseEvent) => {
      setOffset({
        x: dragStart.current.ox + (e.clientX - dragStart.current.x),
        y: dragStart.current.oy + (e.clientY - dragStart.current.y),
      });
    };
    const onUp = () => {
      setDragging(false);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  };

  useEffect(() => {
    if (zoom <= 1) setOffset({ x: 0, y: 0 });
  }, [zoom]);

  if (error) {
    return (
      <div className="flex items-center justify-center h-full">
        <span className="text-sm text-red-500">Failed to load image</span>
      </div>
    );
  }

  return (
    <div className="relative w-full h-full flex flex-col">
      <div
        ref={containerRef}
        className={`flex-1 min-h-0 flex items-center justify-center overflow-hidden bg-[repeating-conic-gradient(hsl(var(--muted))_0%_25%,transparent_0%_50%)] bg-[length:16px_16px] ${
          zoom > 1 ? (dragging ? 'cursor-grabbing' : 'cursor-grab') : 'cursor-zoom-in'
        }`}
        onWheel={onWheel}
        onMouseDown={zoom > 1 ? onMouseDown : undefined}
        onClick={zoom <= 1 ? zoomIn : undefined}
      >
        {!loaded && (
          <div className="absolute inset-0 flex items-center justify-center">
            <Loader2 className="h-6 w-6 text-duck-teal animate-spin" />
          </div>
        )}
        <img
          src={src}
          alt={fileName}
          onLoad={() => setLoaded(true)}
          onError={() => setError(true)}
          className="transition-transform duration-150 select-none"
          draggable={false}
          style={{
            transform: `translate(${offset.x}px, ${offset.y}px) scale(${zoom}) rotate(${rotation}deg)`,
            maxWidth: zoom <= 1 ? '100%' : 'none',
            maxHeight: zoom <= 1 ? '100%' : 'none',
            opacity: loaded ? 1 : 0,
          }}
        />
      </div>

      <div className="shrink-0 flex items-center justify-center gap-1 py-2 border-t border-duck-dark/10 bg-background/80">
        <button
          onClick={zoomOut}
          disabled={zoom <= MIN_ZOOM}
          className="p-1.5 rounded-md text-duck-dark/50 hover:text-duck-dark hover:bg-duck-dark/5 disabled:opacity-30 transition-colors cursor-pointer"
        >
          <ZoomOut className="h-4 w-4" />
        </button>
        <button
          onClick={resetView}
          className="px-2 py-1 rounded-md text-xs font-mono text-duck-dark/50 hover:text-duck-dark hover:bg-duck-dark/5 transition-colors cursor-pointer min-w-[4rem] text-center"
        >
          {Math.round(zoom * 100)}%
        </button>
        <button
          onClick={zoomIn}
          disabled={zoom >= MAX_ZOOM}
          className="p-1.5 rounded-md text-duck-dark/50 hover:text-duck-dark hover:bg-duck-dark/5 disabled:opacity-30 transition-colors cursor-pointer"
        >
          <ZoomIn className="h-4 w-4" />
        </button>
        <div className="w-px h-4 bg-duck-dark/10 mx-1" />
        <button
          onClick={rotate}
          className="p-1.5 rounded-md text-duck-dark/50 hover:text-duck-dark hover:bg-duck-dark/5 transition-colors cursor-pointer"
        >
          <RotateCw className="h-4 w-4" />
        </button>
      </div>
    </div>
  );
};
