import React, { createContext, useContext, useState, useCallback, type PropsWithChildren } from 'react';
import type { IDialogConfig, IDialogInstance, IDialogContextValue } from '../../interfaces/common';
import DialogComponent from './DialogComponent';

// 创建Dialog上下文
export const DialogContext = createContext<IDialogContextValue | null>(null);

// 生成唯一ID的工具函数
const generateId = () => `dialog_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

export const DialogProvider: React.FC<PropsWithChildren> = ({ children }) => {
  const [dialogs, setDialogs] = useState<IDialogInstance[]>([]);

  // 打开对话框的通用方法
  const openDialog = useCallback((config: IDialogConfig): Promise<boolean> => {
    return new Promise((resolve, reject) => {
      const id = generateId();
      const dialogInstance: IDialogInstance = {
        id,
        config,
        resolve,
        reject,
      };

      setDialogs(prev => [...prev, dialogInstance]);
    });
  }, []);

  // 关闭对话框
  const closeDialog = useCallback((id: string, result: boolean = false) => {
    setDialogs(prev => {
      const dialog = prev.find(d => d.id === id);
      if (dialog) {
        dialog.resolve(result);
      }
      return prev.filter(d => d.id !== id);
    });
  }, []);

  // 确认对话框
  const confirm = useCallback((config: Omit<IDialogConfig, 'type'>): Promise<boolean> => {
    return openDialog({
      ...config,
      type: 'confirm',
      showCancel: true,
      confirmText: config.confirmText || '确定',
      cancelText: config.cancelText || '取消',
    });
  }, [openDialog]);

  // 信息对话框
  const info = useCallback((config: Omit<IDialogConfig, 'type'>): Promise<boolean> => {
    return openDialog({
      ...config,
      type: 'info',
      showCancel: false,
      confirmText: config.confirmText || '确定',
    });
  }, [openDialog]);

  // 成功对话框
  const success = useCallback((config: Omit<IDialogConfig, 'type'>): Promise<boolean> => {
    return openDialog({
      ...config,
      type: 'success',
      showCancel: false,
      confirmText: config.confirmText || '确定',
    });
  }, [openDialog]);

  // 警告对话框
  const warning = useCallback((config: Omit<IDialogConfig, 'type'>): Promise<boolean> => {
    return openDialog({
      ...config,
      type: 'warning',
      showCancel: false,
      confirmText: config.confirmText || '确定',
    });
  }, [openDialog]);

  // 错误对话框
  const error = useCallback((config: Omit<IDialogConfig, 'type'>): Promise<boolean> => {
    return openDialog({
      ...config,
      type: 'error',
      showCancel: false,
      confirmText: config.confirmText || '确定',
    });
  }, [openDialog]);

  const contextValue: IDialogContextValue = {
    dialogs,
    openDialog,
    closeDialog,
    confirm,
    info,
    success,
    warning,
    error,
  };

  return (
    <DialogContext.Provider value={contextValue}>
      {children}
      {/* 渲染所有对话框 */}
      {dialogs.map(dialog => (
        <DialogComponent
          key={dialog.id}
          dialog={dialog}
          onClose={(result) => closeDialog(dialog.id, result)}
        />
      ))}
    </DialogContext.Provider>
  );
};

export default DialogProvider;