import { useState, useCallback, useRef } from 'react';
import { UseDragOptions, UseDragReturn } from '../../types';

/**
 * 드래그 기능 훅
 * - 마우스/터치 드래그 지원
 * - 줌 100% 초과 시에만 활성화 권장
 */
export function useDrag(options: UseDragOptions = {}): UseDragReturn {
  const { enabled = true } = options;

  const [isDragging, setIsDragging] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const startPos = useRef({ x: 0, y: 0 });

  // 마우스 드래그 시작
  const onMouseDown = useCallback(
    (e: React.MouseEvent) => {
      if (!enabled) return;
      setIsDragging(true);
      startPos.current = {
        x: e.clientX - position.x,
        y: e.clientY - position.y,
      };
    },
    [enabled, position]
  );

  // 마우스 이동
  const onMouseMove = useCallback(
    (e: React.MouseEvent) => {
      if (!isDragging) return;
      setPosition({
        x: e.clientX - startPos.current.x,
        y: e.clientY - startPos.current.y,
      });
    },
    [isDragging]
  );

  // 마우스 드래그 종료
  const onMouseUp = useCallback(() => {
    setIsDragging(false);
  }, []);

  // 터치 드래그 시작
  const onTouchStart = useCallback(
    (e: React.TouchEvent) => {
      if (!enabled || e.touches.length !== 1) return;
      setIsDragging(true);
      startPos.current = {
        x: e.touches[0].clientX - position.x,
        y: e.touches[0].clientY - position.y,
      };
    },
    [enabled, position]
  );

  // 터치 이동
  const onTouchMove = useCallback(
    (e: React.TouchEvent) => {
      if (!isDragging || e.touches.length !== 1) return;
      setPosition({
        x: e.touches[0].clientX - startPos.current.x,
        y: e.touches[0].clientY - startPos.current.y,
      });
    },
    [isDragging]
  );

  // 터치 종료
  const onTouchEnd = useCallback(() => {
    setIsDragging(false);
  }, []);

  // 위치 리셋
  const resetPosition = useCallback(() => {
    setPosition({ x: 0, y: 0 });
  }, []);

  return {
    position,
    isDragging,
    handlers: {
      onMouseDown,
      onMouseMove,
      onMouseUp,
      onMouseLeave: onMouseUp,
      onTouchStart,
      onTouchMove,
      onTouchEnd,
    },
    resetPosition,
  };
}
