import { useState, useRef, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { InfoV0Modal } from '@/components/InfoV0Modal';
import { ZoomIn, ZoomOut, RotateCcw, Map } from 'lucide-react';

export function IsopletasModal() {
  const [open, setOpen] = useState(false);
  const [scale, setScale] = useState(1);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);
  const dragStart = useRef({ x: 0, y: 0 });
  const containerRef = useRef<HTMLDivElement>(null);
  const touchStartDist = useRef<number | null>(null);

  // Reset zoom on open/close
  useEffect(() => {
    if (!open) {
      handleReset();
    }
  }, [open]);

  const handleZoomIn = () => setScale((s) => Math.min(s + 0.25, 4));
  const handleZoomOut = () => setScale((s) => Math.max(s - 0.25, 0.5));
  const handleReset = () => {
    setScale(1);
    setPosition({ x: 0, y: 0 });
  };

  // Mouse wheel zoom
  const handleWheel = (e: React.WheelEvent) => {
    e.preventDefault();
    const zoomFactor = 0.1;
    if (e.deltaY < 0) {
      setScale((s) => Math.min(s + zoomFactor, 4));
    } else {
      setScale((s) => Math.max(s - zoomFactor, 0.5));
    }
  };

  // Drag pan
  const handleMouseDown = (e: React.MouseEvent) => {
    e.preventDefault();
    setIsDragging(true);
    dragStart.current = { x: e.clientX - position.x, y: e.clientY - position.y };
  };

  const handleMouseMove = (e: React.MouseEvent) => {
    if (!isDragging) return;
    setPosition({
      x: e.clientX - dragStart.current.x,
      y: e.clientY - dragStart.current.y,
    });
  };

  const handleMouseUpOrLeave = () => {
    setIsDragging(false);
  };

  // Touch gestures (Pinch-to-zoom & Drag-to-pan)
  const handleTouchStart = (e: React.TouchEvent) => {
    if (e.touches.length === 1) {
      // Single finger drag
      setIsDragging(true);
      dragStart.current = { x: e.touches[0].clientX - position.x, y: e.touches[0].clientY - position.y };
    } else if (e.touches.length === 2) {
      // Two finger pinch zoom
      const dist = Math.hypot(
        e.touches[0].clientX - e.touches[1].clientX,
        e.touches[0].clientY - e.touches[1].clientY
      );
      touchStartDist.current = dist;
    }
  };

  const handleTouchMove = (e: React.TouchEvent) => {
    if (e.touches.length === 1 && isDragging) {
      setPosition({
        x: e.touches[0].clientX - dragStart.current.x,
        y: e.touches[0].clientY - dragStart.current.y,
      });
    } else if (e.touches.length === 2 && touchStartDist.current !== null) {
      const dist = Math.hypot(
        e.touches[0].clientX - e.touches[1].clientX,
        e.touches[0].clientY - e.touches[1].clientY
      );
      const factor = dist / touchStartDist.current;
      setScale((s) => Math.min(Math.max(s * factor, 0.5), 4));
      touchStartDist.current = dist;
    }
  };

  const handleTouchEnd = () => {
    setIsDragging(false);
    touchStartDist.current = null;
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button
          variant="outline"
          size="icon"
          className="h-8 w-8 text-muted-foreground hover:text-foreground shrink-0 border-primary/20 hover:bg-primary/5"
          title="Ver mapa de isopletas"
        >
          <Map className="h-4 w-4 text-primary" />
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[700px] max-w-[95vw] h-[80vh] flex flex-col p-4 bg-background border border-border shadow-2xl">
        <DialogHeader className="flex-row items-center justify-between pb-2 border-b">
          <div>
            <DialogTitle className="text-sm font-semibold">Mapa de Isopletas (NBR 6123)</DialogTitle>
            <DialogDescription className="text-[10px]">
              Velocidade básica do vento V₀ (m/s). Use a roda do mouse, botões ou gestos de pinça para dar zoom.
            </DialogDescription>
          </div>
          <div className="flex items-center gap-1">
            <InfoV0Modal variant="button" buttonText="Atenção" className="mr-1" />
            <Button variant="ghost" size="icon" className="h-8 w-8" onClick={handleZoomIn} title="Aproximar">
              <ZoomIn className="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="icon" className="h-8 w-8" onClick={handleZoomOut} title="Afastar">
              <ZoomOut className="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="icon" className="h-8 w-8" onClick={handleReset} title="Resetar Visualização">
              <RotateCcw className="h-4 w-4" />
            </Button>
          </div>
        </DialogHeader>

        <div
          ref={containerRef}
          className="flex-1 w-full h-full overflow-hidden relative cursor-grab active:cursor-grabbing bg-slate-950 rounded-md mt-2 flex items-center justify-center touch-none select-none"
          onWheel={handleWheel}
          onMouseDown={handleMouseDown}
          onMouseMove={handleMouseMove}
          onMouseUp={handleMouseUpOrLeave}
          onMouseLeave={handleMouseUpOrLeave}
          onTouchStart={handleTouchStart}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
        >
          <img
            src="/isopletas.png"
            alt="Mapa de Isopletas NBR 6123"
            className="max-w-full max-h-full object-contain transition-transform duration-75 pointer-events-none"
            style={{
              transform: `translate(${position.x}px, ${position.y}px) scale(${scale})`,
              transformOrigin: 'center center',
            }}
          />
        </div>
      </DialogContent>
    </Dialog>
  );
}
