import { useState, useMemo } from 'react';
import IconButton from '@mui/material/IconButton';
import FontAwesome from '@/shared/components/fontawesome';
import { faBell } from '@fortawesome/free-solid-svg-icons';
import { Badge, Popover, Box, Tabs, Tab, Typography, Stack, IconButton as MuiIconButton, Menu, MenuItem, ListItemIcon, ListItemText, FormGroup, FormControlLabel, Checkbox } from '@mui/material';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { WhiteIconButtonStyle } from '@/shared/theme/css';
import { Close, MoreVert as MoreIcon, DoneAll as DoneAllIcon, DeleteSweep as DeleteIcon, Settings as SettingsIcon } from '@mui/icons-material';
import { mockNotifications, getNotificationsByType, getUnreadCount } from '@/shared/_mock/notifications';
import { 
  AutoAwesome as AutomationIcon,
  AlternateEmail as MentionIcon,
  Assignment as AssignmentIcon 
} from '@mui/icons-material';
import { alpha } from '@mui/material/styles';

// ----------------------------------------------------------------------

const getNotificationIcon = (type: 'automation' | 'mention' | 'assignment') => {
  switch (type) {
    case 'automation':
      return <AutomationIcon sx={{ color: 'warning.main' }} />;
    case 'mention':
      return <MentionIcon sx={{ color: 'info.main' }} />;
    case 'assignment':
      return <AssignmentIcon sx={{ color: 'success.main' }} />;
    default:
      return null;
  }
};

export default function NotificationPopover() {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [currentTab, setCurrentTab] = useState(0);
  const [notifications, setNotifications] = useState(mockNotifications);
  const unreadCount = getUnreadCount();
  const [menuAnchorEl, setMenuAnchorEl] = useState<null | HTMLElement>(null);
  const isMenuOpen = Boolean(menuAnchorEl);
  const [showUnread, setShowUnread] = useState(false);
  const [showRead, setShowRead] = useState(false);

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setCurrentTab(newValue);
  };

  const handleMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
    setMenuAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setMenuAnchorEl(null);
  };

  const handleMarkAllRead = () => {
    // Add your logic here
    handleMenuClose();
  };

  const handleDeleteAll = () => {
    // Add your logic here
    handleMenuClose();
  };

  const handleSettings = () => {
    // Add your logic here
    handleMenuClose();
  };

  const open = Boolean(anchorEl);

  const filteredNotifications = useMemo(() => {
    let filtered = notifications;

    // Filter by type (all/mention)
    if (currentTab === 1) { // mention tab
      filtered = filtered.filter(notif => notif.type === 'mention');
    }

    // Filter by read/unread status
    if (showUnread && !showRead) {
      filtered = filtered.filter(notif => !notif.read);
    } else if (showRead && !showUnread) {
      filtered = filtered.filter(notif => notif.read);
    }

    return filtered;
  }, [currentTab, notifications, showRead, showUnread]);

  return (
    <>
      <CustomTooltip title="Notifications" arrow>
        <IconButton sx={WhiteIconButtonStyle} onClick={handleClick}>
          <Badge
            badgeContent={unreadCount}
            sx={{
              '& .MuiBadge-badge': {
                height: '15px',
                fontSize: '0.7rem',
                minWidth: '15px',
                px: 0,
                mr: '18%',
                bgcolor: 'error.main',
                color: 'white',
              },
            }}
            color="error"
          >
            <FontAwesome icon={faBell} />
          </Badge>
        </IconButton>
      </CustomTooltip>

      <Popover
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
        PaperProps={{
          sx: { 
            width: 480, 
            p: 0,
            boxShadow: (theme) => theme.shadows[8],
            borderRadius: 2,
            overflow: 'hidden',
            position: 'fixed',
            maxHeight: 'calc(100vh - 100px)',
            mt: 1
          },
        }}
      >
        {/* Fixed Header Section */}
        <Box
          sx={{
            position: 'sticky',
            top: 0,
            zIndex: 1,
            bgcolor: 'background.paper',
          }}
        >
          {/* Title and Close Button */}
          <Box 
            sx={{ 
              p: 2, 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'space-between',
              bgcolor: 'primary.main',
              color: 'white'
            }}
          >
            <Typography variant="h6" sx={{ fontWeight: 600, fontSize: '1.1rem' }}>
              Notifications
            </Typography>
            <Box sx={{ display: 'flex', gap: 1 }}>
              <MuiIconButton size="small" onClick={handleMenuOpen} sx={{ color: 'white' }}>
                <MoreIcon />
              </MuiIconButton>
              <MuiIconButton size="small" onClick={handleClose} sx={{ color: 'white' }}>
                <Close />
              </MuiIconButton>
            </Box>
          </Box>

          {/* Tabs */}
          <Tabs 
            value={currentTab} 
            onChange={handleTabChange} 
            sx={{ 
              px: 2,
              borderBottom: 1,
              borderColor: 'divider',
              bgcolor: 'background.paper',
              '& .MuiTab-root': {
                textTransform: 'none',
                fontWeight: 500,
                fontSize: '0.9rem',
                minHeight: 48,
                color: 'text.secondary',
                '&.Mui-selected': {
                  color: 'primary.main',
                },
              },
              '& .MuiTabs-indicator': {
                backgroundColor: 'primary.main',
              },
            }}
          >
            <Tab label="Tous" />
            <Tab label="a mentionné" />
          </Tabs>

          {/* Checkboxes and Search */}
          <Box sx={{ 
            p: 2, 
            bgcolor: 'background.paper',
            borderBottom: 1,
            borderColor: 'divider',
          }}>
            <Stack spacing={2}>
              <FormGroup row sx={{ gap: 2 }}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={showUnread}
                      onChange={(e) => setShowUnread(e.target.checked)}
                      size="small"
                    />
                  }
                  label="Non lu"
                />
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={showRead}
                      onChange={(e) => setShowRead(e.target.checked)}
                      size="small"
                    />
                  }
                  label="Lu"
                />
              </FormGroup>

              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <input
                  type="text"
                  placeholder="Rechercher toutes les notifications"
                  style={{
                    width: '100%',
                    padding: '10px 12px',
                    border: '1px solid #ddd',
                    borderRadius: '8px',
                    fontSize: '0.875rem',
                    backgroundColor: 'white',
                    outline: 'none',
                    transition: 'all 0.2s',
                  }}
                />
              </Box>
            </Stack>
          </Box>
        </Box>

        {/* Move the Menu outside the fixed header section and place it right after the Popover opening tag */}
        <Menu
          anchorEl={menuAnchorEl}
          open={isMenuOpen}
          onClose={handleMenuClose}
          transformOrigin={{ horizontal: 'right', vertical: 'top' }}
          anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
          PaperProps={{
            sx: {
              mt: 1,
              width: 250,
              '& .MuiMenuItem-root': {
                px: 2,
                py: 1,
                typography: 'body2',
                borderRadius: 0.75,
              },
            },
          }}
        >
          <MenuItem onClick={handleMarkAllRead}>
            <ListItemIcon>
              <DoneAllIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText 
              primary="Tout marquer comme lu"
              primaryTypographyProps={{ variant: 'body2' }}
            />
          </MenuItem>

          <MenuItem onClick={handleDeleteAll}>
            <ListItemIcon>
              <DeleteIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText 
              primary="Tout supprimer"
              primaryTypographyProps={{ variant: 'body2' }}
            />
          </MenuItem>

          <MenuItem onClick={handleSettings}>
            <ListItemIcon>
              <SettingsIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText 
              primary="Modifier les paramètres des notifications"
              primaryTypographyProps={{ 
                variant: 'body2',
                sx: { whiteSpace: 'normal' }
              }}
            />
          </MenuItem>
        </Menu>

        {/* Scrollable Notifications List */}
        <Box sx={{ 
          overflowY: 'auto',
          maxHeight: 'calc(100vh - 300px)', // Adjust this value based on your header height
          bgcolor: alpha('#F4F6F8', 0.8),
          p: 2
        }}>
          <Stack spacing={2}>
            {filteredNotifications.map((notification) => (
              <Box 
                key={notification.id}
                sx={{ 
                  bgcolor: notification.read ? 'white' : alpha('#E3F2FD', 0.5),
                  p: 2,
                  borderRadius: 2,
                  cursor: 'pointer',
                  transition: 'all 0.2s',
                  border: '1px solid',
                  borderColor: notification.read ? 'transparent' : alpha('#90CAF9', 0.2),
                  '&:hover': {
                    bgcolor: notification.read ? alpha('#F5F5F5', 0.8) : alpha('#E3F2FD', 0.8),
                    boxShadow: (theme) => theme.shadows[1],
                  },
                }}
              >
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                  {getNotificationIcon(notification.type)}
                  <Typography 
                    variant="subtitle2" 
                    sx={{ 
                      fontWeight: notification.read ? 500 : 600,
                      color: 'text.primary'
                    }}
                  >
                    {notification.title}
                  </Typography>
                </Box>
                <Typography 
                  variant="body2" 
                  color="text.secondary"
                  sx={{ 
                    fontSize: '0.875rem',
                    lineHeight: 1.5
                  }}
                >
                  {notification.description}
                </Typography>
                {notification.link && (
                  <Typography 
                    variant="body2" 
                    color="primary" 
                    sx={{ 
                      mt: 1,
                      fontWeight: 500,
                      fontSize: '0.875rem',
                      '&:hover': {
                        textDecoration: 'underline'
                      }
                    }}
                  >
                    Voir plus
                  </Typography>
                )}
                <Typography 
                  variant="caption" 
                  color="text.secondary" 
                  sx={{ 
                    display: 'block', 
                    mt: 1,
                    fontSize: '0.75rem'
                  }}
                >
                  {notification.timestamp}
                </Typography>
              </Box>
            ))}
          </Stack>
        </Box>
      </Popover>
    </>
  );
}
