import React, { createContext, useContext, useState, useCallback } from 'react';
import { Snackbar, Alert, AlertTitle, IconButton, Box, Collapse } from '@mui/material';
import { Close, ExpandMore, ExpandLess } from '@mui/icons-material';

const SecurityNotificationContext = createContext();

export const useSecurityNotification = () => {
  const context = useContext(SecurityNotificationContext);
  if (!context) {
    throw new Error('useSecurityNotification must be used within SecurityNotificationProvider');
  }
  return context;
};

export const SecurityNotificationProvider = ({ children }) => {
  const [notifications, setNotifications] = useState([]);

  const addNotification = useCallback(({
    type = 'info', // 'success', 'info', 'warning', 'error'
    title,
    message,
    details,
    duration = 6000,
    persistent = false
  }) => {
    const id = Date.now() + Math.random();
    const notification = {
      id,
      type,
      title,
      message,
      details,
      duration,
      persistent,
      expanded: false,
      timestamp: new Date()
    };

    setNotifications(prev => [...prev, notification]);

    if (!persistent && duration > 0) {
      setTimeout(() => {
        removeNotification(id);
      }, duration);
    }

    return id;
  }, []);

  const removeNotification = useCallback((id) => {
    setNotifications(prev => prev.filter(n => n.id !== id));
  }, []);

  const toggleExpanded = useCallback((id) => {
    setNotifications(prev =>
      prev.map(n => n.id === id ? { ...n, expanded: !n.expanded } : n)
    );
  }, []);

  // Specific notification types for security events
  const notifySecurityWarning = useCallback((message, details) => {
    return addNotification({
      type: 'warning',
      title: 'Security Warning',
      message,
      details,
      duration: 8000
    });
  }, [addNotification]);

  const notifySecurityError = useCallback((message, details) => {
    return addNotification({
      type: 'error',
      title: 'Security Alert',
      message,
      details,
      persistent: true
    });
  }, [addNotification]);

  const notifyAccountLocked = useCallback((remainingMinutes) => {
    return addNotification({
      type: 'error',
      title: 'Account Locked',
      message: `Your account has been locked due to multiple failed login attempts.`,
      details: `Please try again in ${remainingMinutes} minutes.`,
      persistent: true
    });
  }, [addNotification]);

  const notifyPasswordExpiring = useCallback((daysRemaining) => {
    return addNotification({
      type: 'warning',
      title: 'Password Expiring Soon',
      message: `Your password will expire in ${daysRemaining} day${daysRemaining !== 1 ? 's' : ''}.`,
      details: 'Please change your password to maintain account security.',
      duration: 10000
    });
  }, [addNotification]);

  const notifyInvalidInput = useCallback((fieldName, errors) => {
    return addNotification({
      type: 'error',
      title: 'Invalid Input',
      message: `Please check the ${fieldName} field.`,
      details: Array.isArray(errors) ? errors.join(', ') : errors,
      duration: 5000
    });
  }, [addNotification]);

  const notifySecuritySuccess = useCallback((message) => {
    return addNotification({
      type: 'success',
      title: 'Security Update',
      message,
      duration: 4000
    });
  }, [addNotification]);

  const value = {
    addNotification,
    removeNotification,
    notifySecurityWarning,
    notifySecurityError,
    notifyAccountLocked,
    notifyPasswordExpiring,
    notifyInvalidInput,
    notifySecuritySuccess
  };

  return (
    <SecurityNotificationContext.Provider value={value}>
      {children}
      <Box
        sx={{
          position: 'fixed',
          top: 80,
          right: 24,
          zIndex: 9999,
          maxWidth: 400,
          width: '100%'
        }}
      >
        {notifications.map((notification, index) => (
          <Snackbar
            key={notification.id}
            open={true}
            anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
            sx={{
              position: 'relative',
              mt: index * 0.5,
              mb: 1
            }}
          >
            <Alert
              severity={notification.type}
              onClose={() => removeNotification(notification.id)}
              sx={{
                width: '100%',
                boxShadow: 3,
                '& .MuiAlert-message': {
                  width: '100%'
                }
              }}
              action={
                <IconButton
                  size="small"
                  aria-label="close"
                  color="inherit"
                  onClick={() => removeNotification(notification.id)}
                >
                  <Close fontSize="small" />
                </IconButton>
              }
            >
              {notification.title && (
                <AlertTitle sx={{ fontWeight: 600 }}>
                  {notification.title}
                </AlertTitle>
              )}
              <Box>
                {notification.message}
                {notification.details && (
                  <>
                    {notification.details.length > 100 ? (
                      <>
                        <IconButton
                          size="small"
                          onClick={() => toggleExpanded(notification.id)}
                          sx={{ ml: 1, p: 0 }}
                        >
                          {notification.expanded ? <ExpandLess /> : <ExpandMore />}
                        </IconButton>
                        <Collapse in={notification.expanded}>
                          <Box sx={{ mt: 1, fontSize: '0.875rem', opacity: 0.9 }}>
                            {notification.details}
                          </Box>
                        </Collapse>
                      </>
                    ) : (
                      <Box sx={{ mt: 0.5, fontSize: '0.875rem', opacity: 0.9 }}>
                        {notification.details}
                      </Box>
                    )}
                  </>
                )}
              </Box>
            </Alert>
          </Snackbar>
        ))}
      </Box>
    </SecurityNotificationContext.Provider>
  );
};

export default SecurityNotificationProvider;
