import React, { createContext, useContext, useState, useCallback } from 'react';
import { Snackbar, Alert, AlertTitle, IconButton } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { useTranslation } from 'react-i18next';
import { getErrorMessage, getErrorType, getErrorSeverity } from '../utils/errorHandler';

const ErrorNotificationContext = createContext(null);

/**
 * Error Notification Provider
 * Provides global error notification functionality throughout the app
 */
export function ErrorNotificationProvider({ children }) {
  const { t } = useTranslation();
  const [notification, setNotification] = useState(null);

  /**
   * Show error notification from error object
   */
  const showError = useCallback((error, options = {}) => {
    const {
      title,
      defaultMessage = t('errors.general.unexpected'),
      duration = 6000
    } = options;

    const message = getErrorMessage(error, defaultMessage);
    const type = getErrorType(error);
    const severity = getErrorSeverity(error);

    // Get translated title based on error type
    const errorTitle = title || getErrorTitle(type, t);

    setNotification({
      message,
      title: errorTitle,
      severity,
      duration,
      timestamp: Date.now()
    });
  }, [t]);

  /**
   * Show success notification
   */
  const showSuccess = useCallback((message, options = {}) => {
    const { title, duration = 4000 } = options;

    setNotification({
      message,
      title,
      severity: 'success',
      duration,
      timestamp: Date.now()
    });
  }, []);

  /**
   * Show warning notification
   */
  const showWarning = useCallback((message, options = {}) => {
    const { title, duration = 5000 } = options;

    setNotification({
      message,
      title,
      severity: 'warning',
      duration,
      timestamp: Date.now()
    });
  }, []);

  /**
   * Show info notification
   */
  const showInfo = useCallback((message, options = {}) => {
    const { title, duration = 4000 } = options;

    setNotification({
      message,
      title,
      severity: 'info',
      duration,
      timestamp: Date.now()
    });
  }, []);

  /**
   * Clear notification
   */
  const clearNotification = useCallback(() => {
    setNotification(null);
  }, []);

  const handleClose = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    clearNotification();
  };

  const value = {
    showError,
    showSuccess,
    showWarning,
    showInfo,
    clearNotification
  };

  return (
    <ErrorNotificationContext.Provider value={value}>
      {children}
      
      {notification && (
        <Snackbar
          open={true}
          autoHideDuration={notification.duration}
          onClose={handleClose}
          anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
          sx={{ mt: 8 }}
        >
          <Alert
            onClose={handleClose}
            severity={notification.severity}
            variant="filled"
            sx={{ width: '100%', maxWidth: 500 }}
            action={
              <IconButton
                size="small"
                aria-label="close"
                color="inherit"
                onClick={handleClose}
              >
                <CloseIcon fontSize="small" />
              </IconButton>
            }
          >
            {notification.title && (
              <AlertTitle>{notification.title}</AlertTitle>
            )}
            {notification.message}
          </Alert>
        </Snackbar>
      )}
    </ErrorNotificationContext.Provider>
  );
}

/**
 * Get error title based on error type
 */
function getErrorTitle(type, t) {
  const titles = {
    auth: t('errors.auth.title'),
    permission: t('errors.permission.title'),
    validation: t('errors.validation.title'),
    network: t('errors.network.title'),
    server: t('errors.server.title'),
    unknown: t('error')
  };

  return titles[type] || titles.unknown;
}

/**
 * Hook to use error notifications
 */
export function useErrorNotification() {
  const context = useContext(ErrorNotificationContext);
  
  if (!context) {
    throw new Error('useErrorNotification must be used within ErrorNotificationProvider');
  }
  
  return context;
}

export default ErrorNotificationProvider;
