import React, { createContext, useContext } from 'react';

import { useDialog, type ActionSheetConfig, type ActionSheetOption, type DialogConfig } from '@/hooks/useDialog';
import { ActionSheet } from './ActionSheet';
import { ConfirmDialog } from './ConfirmDialog';


interface DialogContextType {
  showConfirm: (config: DialogConfig, onConfirm: () => void) => void;
  showActionSheet: (config: ActionSheetConfig, options: ActionSheetOption[]) => void;
}

const DialogContext = createContext<DialogContextType | null>(null);

export function DialogProvider({ children }: { children: React.ReactNode }) {
  const {
    confirmDialog,
    showConfirm,
    hideConfirm,
    actionSheet,
    showActionSheet,
    hideActionSheet,
  } = useDialog();

  const contextValue: DialogContextType = {
    showConfirm,
    showActionSheet,
  };

  return (
    <DialogContext.Provider value={contextValue}>
      {children}
      
      {/* 确认弹窗 */}
      <ConfirmDialog
        visible={confirmDialog.visible}
        onClose={hideConfirm}
        title={confirmDialog.config.title}
        message={confirmDialog.config.message}
        confirmText={confirmDialog.config.confirmText}
        cancelText={confirmDialog.config.cancelText}
        onConfirm={confirmDialog.onConfirm}
        destructive={confirmDialog.config.destructive}
        icon={confirmDialog.config.icon}
        iconColor={confirmDialog.config.iconColor}
      />

      {/* ActionSheet */}
      <ActionSheet
        visible={actionSheet.visible}
        onClose={hideActionSheet}
        title={actionSheet.config.title}
        subtitle={actionSheet.config.subtitle}
        cancelText={actionSheet.config.cancelText}
        options={actionSheet.options}
      />
    </DialogContext.Provider>
  );
}

export function useGlobalDialog() {
  const context = useContext(DialogContext);
  if (!context) {
    throw new Error('useGlobalDialog must be used within a DialogProvider');
  }
  return context;
}