import { useState, useCallback } from 'react';
import { UseZoomOptions, UseZoomReturn } from '../../types';

const DEFAULT_ZOOM_LEVELS = [50, 75, 100, 125, 150, 200];
const DEFAULT_MIN_ZOOM = 50;
const DEFAULT_MAX_ZOOM = 200;
const DEFAULT_ZOOM = 100;

/**
 * 줌 기능 훅
 * - 단계별 줌 인/아웃
 * - 맞춤(리셋) 기능
 */
export function useZoom(options: UseZoomOptions = {}): UseZoomReturn {
  const {
    defaultZoom = DEFAULT_ZOOM,
    minZoom = DEFAULT_MIN_ZOOM,
    maxZoom = DEFAULT_MAX_ZOOM,
    zoomLevels = DEFAULT_ZOOM_LEVELS,
  } = options;

  const [zoom, setZoomState] = useState(defaultZoom);

  // 줌 인 - 다음 단계로
  const zoomIn = useCallback(() => {
    setZoomState((prev) => {
      const nextIndex = zoomLevels.findIndex((z) => z > prev);
      return nextIndex !== -1 ? zoomLevels[nextIndex] : maxZoom;
    });
  }, [zoomLevels, maxZoom]);

  // 줌 아웃 - 이전 단계로
  const zoomOut = useCallback(() => {
    setZoomState((prev) => {
      const prevIndex = zoomLevels.slice().reverse().findIndex((z) => z < prev);
      const index = prevIndex !== -1 ? zoomLevels.length - 1 - prevIndex : 0;
      return zoomLevels[index] || minZoom;
    });
  }, [zoomLevels, minZoom]);

  // 줌 리셋 - 100%로
  const zoomReset = useCallback(() => {
    setZoomState(100);
  }, []);

  // 직접 줌 설정
  const setZoom = useCallback(
    (newZoom: number) => {
      setZoomState(Math.min(Math.max(newZoom, minZoom), maxZoom));
    },
    [minZoom, maxZoom]
  );

  return {
    zoom,
    zoomIn,
    zoomOut,
    zoomReset,
    setZoom,
    canZoomIn: zoom < maxZoom,
    canZoomOut: zoom > minZoom,
  };
}
