import React, { createContext, useContext, useState, useCallback, type PropsWithChildren } from 'react';
import { useTranslation } from 'react-i18next';
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 { t } = useTranslation();

  // 打开对话框的通用方法
  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 || t('common.confirm'),
      cancelText: config.cancelText || t('common.cancel'),
    });
  }, [openDialog, t]);

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

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

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

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

  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;