import React, { createContext, useContext, useState, useCallback, useEffect, type PropsWithChildren } from 'react';
import { Snackbar, Alert, type AlertColor } from '@mui/material';

interface SnackbarItem {
  id: string;
  message: string;
  severity: AlertColor;
  duration?: number;
  title?: string;
}

interface SnackbarContextType {
  showSnackbar: (snackbar: Omit<SnackbarItem, 'id'>) => void;
  showMessage: {
    success: (message: string, duration?: number) => void;
    error: (message: string, duration?: number) => void;
    warning: (message: string, duration?: number) => void;
    info: (message: string, duration?: number) => void;
  };
  showNotification: {
    success: (title: string, message?: string, duration?: number) => void;
    error: (title: string, message?: string, duration?: number) => void;
    warning: (title: string, message?: string, duration?: number) => void;
    info: (title: string, message?: string, duration?: number) => void;
  };
}

const SnackbarContext = createContext<SnackbarContextType | null>(null);

export const useSnackbar = () => {
  const context = useContext(SnackbarContext);
  if (!context) {
    throw new Error('useSnackbar must be used within SnackbarProvider');
  }
  return context;
};

export default function SnackbarProvider({ children }: PropsWithChildren) {
  const [snackbars, setSnackbars] = useState<SnackbarItem[]>([]);

  const showSnackbar = useCallback((snackbar: Omit<SnackbarItem, 'id'>) => {
    const id = Date.now().toString();
    const newSnackbar = { ...snackbar, id };
    setSnackbars(prev => [...prev, newSnackbar]);
  }, []);

  const removeSnackbar = useCallback((id: string) => {
    setSnackbars(prev => prev.filter(snackbar => snackbar.id !== id));
  }, []);

  const showMessage = {
    success: (message: string, duration = 2000) => 
      showSnackbar({ message, severity: 'success', duration }),
    error: (message: string, duration = 4000) => 
      showSnackbar({ message, severity: 'error', duration }),
    warning: (message: string, duration = 3000) => 
      showSnackbar({ message, severity: 'warning', duration }),
    info: (message: string, duration = 2000) => 
      showSnackbar({ message, severity: 'info', duration }),
  };

  const showNotification = {
    success: (title: string, message?: string, duration = 5000) => 
      showSnackbar({ title, message: message || title, severity: 'success', duration }),
    error: (title: string, message?: string, duration = 6000) => 
      showSnackbar({ title, message: message || title, severity: 'error', duration }),
    warning: (title: string, message?: string, duration = 5000) => 
      showSnackbar({ title, message: message || title, severity: 'warning', duration }),
    info: (title: string, message?: string, duration = 4000) => 
      showSnackbar({ title, message: message || title, severity: 'info', duration }),
  };

  // 为非组件文件提供全局实例
  useEffect(() => {
    if (typeof window !== 'undefined') {
      (window as any).__snackbarInstance = { showSnackbar, showMessage, showNotification };
    }
  }, [showSnackbar, showMessage, showNotification]);

  return (
    <SnackbarContext.Provider value={{ showSnackbar, showMessage, showNotification }}>
      {children}
      {snackbars.map((snackbar, index) => (
        <Snackbar
          key={snackbar.id}
          open={true}
          autoHideDuration={snackbar.duration}
          onClose={() => removeSnackbar(snackbar.id)}
          anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
          sx={{ 
            top: `${80 + index * 70}px !important`,
            zIndex: 9999 - index 
          }}
        >
          <Alert 
            onClose={() => removeSnackbar(snackbar.id)} 
            severity={snackbar.severity}
            variant="filled"
            sx={{ 
              minWidth: 300,
              alignItems: snackbar.title ? 'flex-start' : 'center'
            }}
          >
            {snackbar.title && (
              <div style={{ fontWeight: 600, marginBottom: 4 }}>
                {snackbar.title}
              </div>
            )}
            {snackbar.message}
          </Alert>
        </Snackbar>
      ))}
    </SnackbarContext.Provider>
  );
}
