import { useState, useCallback } from 'react';

interface UseModalReturn<T = any> {
  visible: boolean;
  data: T | null;
  open: (data?: T) => void;
  close: () => void;
  toggle: () => void;
}

/**
 * 弹窗管理Hook
 * 统一处理弹窗的显示/隐藏和数据传递
 */
export function useModal<T = any>(initialVisible = false): UseModalReturn<T> {
  const [visible, setVisible] = useState(initialVisible);
  const [data, setData] = useState<T | null>(null);

  const open = useCallback((modalData?: T) => {
    setVisible(true);
    if (modalData !== undefined) {
      setData(modalData);
    }
  }, []);

  const close = useCallback(() => {
    setVisible(false);
    setData(null);
  }, []);

  const toggle = useCallback(() => {
    setVisible((prev) => !prev);
  }, []);

  return {
    visible,
    data,
    open,
    close,
    toggle,
  };
}
