import { useState, useRef } from 'react';
import { m } from 'framer-motion';
import {
  IconButton,
  Avatar,
  Popover,
  Box,
  Typography,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Divider,
  Paper,
  Stack,
  Menu,
  MenuItem,
} from '@mui/material';
import { alpha } from '@mui/material/styles';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import CloseIcon from '@mui/icons-material/Close';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import VpnKeyIcon from '@mui/icons-material/VpnKey';
import FolderIcon from '@mui/icons-material/Folder';
import BrushIcon from '@mui/icons-material/Brush';
import LogoutIcon from '@mui/icons-material/Logout';
import LightModeIcon from '@mui/icons-material/LightMode';
import DarkModeIcon from '@mui/icons-material/DarkMode';
import SettingsIcon from '@mui/icons-material/Settings';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import { useRouter, usePathname } from 'next/navigation';
import { paths } from '@/routes/paths';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useAuthStore } from '@/shared/api/stores/authStore';

export default function AccountPopover() {
  const anchorRef = useRef(null);
  const themeButtonRef = useRef(null);
  const [open, setOpen] = useState(false);
  const [themeMenuOpen, setThemeMenuOpen] = useState(false);
  const [theme, setTheme] = useState('default');
  const router = useRouter();
  const pathname = usePathname();

  const userName = typeof window !== 'undefined' ? localStorage.getItem('userName') : '';
  const userEmail = typeof window !== 'undefined' ? localStorage.getItem('userEmail') : '';

  const user = {
    displayName: userName || 'Utilisateur',
    email: userEmail || '',
    professionalEmail: userEmail || '',
    photoURL: '/assets/images/profile-img.png',
    initials: userName
      ? userName
          .split(' ')
          .map((n) => n[0])
          .join('')
          .toUpperCase()
      : 'U',
  };

  const isActivePath = (targetPath: string) => {
    return pathname === targetPath;
  };

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const { logout, error } = useAuthStore();

  const handleLogout = async () => {
    handleClose();
    if (!error) {
      await logout();
      const returnTo = encodeURIComponent(window.location.pathname);
      router.replace(`${paths.auth.jwt.login}?returnTo=${returnTo}`);
    }
  };
  const handleThemeMenuOpen = (event: any) => {
    setThemeMenuOpen(true);
  };

  const handleThemeMenuClose = () => {
    setThemeMenuOpen(false);
  };

  const handleThemeChange = (newTheme: any) => {
    setTheme(newTheme);
    handleThemeMenuClose();
  };

  const getActiveStyle = (targetPath: string) => {
    return isActivePath(targetPath)
      ? {
          py: 1,
          backgroundColor: alpha('#746CD4', 0.2),
          borderRadius: 2,
          color: '#746CD4',
        }
      : {
          py: 1,
          borderRadius: 2,
        };
  };

  return (
    <>
      <CustomTooltip title="Profil utilisateur" arrow>
        <IconButton
          ref={anchorRef}
          onClick={handleOpen}
          component={m.button}
          whileTap="tap"
          whileHover="hover"
          variants={{
            tap: { scale: 0.95 },
            hover: { scale: 1.05 },
          }}
          sx={{
            width: 40,
            height: 40,
            background: (theme) => alpha(theme.palette.grey[500], 0.08),
          }}
        >
          <Avatar
            src={user.photoURL}
            alt={user.displayName}
            sx={{
              width: 36,
              height: 36,
              border: (theme) => `solid 2px ${theme.palette.background.default}`,
              bgcolor: 'success.main',
              color: 'white',
            }}
          >
            {user.initials}
          </Avatar>
        </IconButton>
      </CustomTooltip>

      <Popover
        open={open}
        anchorEl={anchorRef.current}
        onClose={handleClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
        PaperProps={{
          sx: {
            p: 0,
            mt: 1.5,
            ml: 0.75,
            width: 320,
            borderRadius: 3,
            boxShadow: (theme) => theme.shadows[8],
            bgcolor: 'background.paper',
          },
        }}
      >
        <Paper
          elevation={0}
          sx={{
            p: 2,
            pb: 3,
            bgcolor: 'background.paper',
            borderRadius: 3,
          }}
        >
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              mb: 2,
            }}
          >
            <Typography variant="body2" color="text.secondary">
              {user.professionalEmail}
            </Typography>
            <IconButton size="small" onClick={handleClose}>
              <CloseIcon fontSize="small" />
            </IconButton>
          </Box>

          <Stack direction="column" alignItems="center" spacing={1} sx={{ mb: 2 }}>
            <Avatar
              src={user.photoURL}
              alt={user.displayName}
              sx={{
                width: 80,
                height: 80,
                mb: 1,
                bgcolor: 'primary.main',
                boxShadow: '0 0 0 4px rgba(255,255,255,0.2)',
                '&::after': {
                  content: '""',
                  position: 'absolute',
                  width: '100%',
                  height: '100%',
                  borderRadius: '50%',
                  border: '4px solid transparent',
                  borderTopColor: 'primary.light',
                  borderRightColor: 'error.main',
                  borderBottomColor: 'warning.main',
                  borderLeftColor: 'info.main',
                },
              }}
            >
              {user.initials}
            </Avatar>
            <Typography variant="h6">
              Salut, {user.displayName.split(' ')[0] || 'Utilisateur'}!
            </Typography>
            <Typography variant="body2" color="text.secondary">
              {user.email}
            </Typography>
          </Stack>

          <Divider sx={{ my: 1.5 }} />

          <List disablePadding>
            <ListItemButton
              onClick={() => {
                router.push(paths.dashboard.staff.profilDetails);
                handleClose();
              }}
              sx={getActiveStyle(paths.dashboard.staff.profilDetails)}
            >
              <ListItemIcon>
                <AccountCircleIcon
                  color={isActivePath(paths.dashboard.staff.profilDetails) ? 'primary' : 'inherit'}
                  fontSize="small"
                />
              </ListItemIcon>
              <ListItemText primary="Mon profil" />
            </ListItemButton>

            <ListItemButton
              onClick={() => {
                router.push(paths.dashboard.staff.profilpassword);
                handleClose();
              }}
              sx={getActiveStyle(paths.dashboard.staff.profilpassword)}
            >
              <ListItemIcon>
                <VpnKeyIcon
                  color={isActivePath(paths.dashboard.staff.profilpassword) ? 'primary' : 'inherit'}
                  fontSize="small"
                />
              </ListItemIcon>
              <ListItemText primary="Changer mot de passe" />
            </ListItemButton>

            <ListItemButton
              onClick={() => {
                router.push(paths.dashboard.staff.document);
                handleClose();
              }}
              sx={getActiveStyle(paths.dashboard.staff.document)}
            >
              <ListItemIcon>
                <FolderIcon
                  color={isActivePath(paths.dashboard.staff.document) ? 'primary' : 'inherit'}
                  fontSize="small"
                />
              </ListItemIcon>
              <ListItemText primary="Mes documents" />
            </ListItemButton>

            <ListItemButton
              onClick={handleThemeMenuOpen}
              ref={themeButtonRef}
              sx={{
                borderRadius: 2,
                py: 1,
              }}
            >
              <ListItemIcon>
                <BrushIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText primary="Thème" />
            </ListItemButton>
          </List>

          <Divider sx={{ my: 1.5 }} />

          <ListItemButton
            onClick={handleLogout}
            sx={{
              borderRadius: 2,
              py: 1,
            }}
          >
            <ListItemIcon>
              <LogoutIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText primary="Déconnexion" />
          </ListItemButton>
        </Paper>
      </Popover>

      <Menu
        anchorEl={themeButtonRef.current}
        open={themeMenuOpen}
        onClose={handleThemeMenuClose}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'left' }}
        PaperProps={{
          sx: {
            p: 1,
            width: 200,
            borderRadius: 2,
            boxShadow: (theme) => theme.shadows[4],
          },
        }}
      >
        <MenuItem
          onClick={() => handleThemeChange('light')}
          sx={{
            borderRadius: 1,
            py: 1.5,
            display: 'flex',
            justifyContent: 'space-between',
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <LightModeIcon fontSize="small" sx={{ mr: 2, color: 'primary.main' }} />
            <Typography variant="body2">Clair</Typography>
          </Box>
          <ConditionalComponent isValid={theme === 'light'} defaultComponent={null}>
            <CheckCircleIcon fontSize="small" sx={{ color: 'primary.main' }} />
          </ConditionalComponent>
        </MenuItem>

        <MenuItem
          onClick={() => handleThemeChange('dark')}
          sx={{
            borderRadius: 1,
            py: 1.5,
            display: 'flex',
            justifyContent: 'space-between',
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <DarkModeIcon fontSize="small" sx={{ mr: 2, color: 'text.primary' }} />
            <Typography variant="body2">Sombre</Typography>
          </Box>
          <ConditionalComponent isValid={theme === 'dark'} defaultComponent={null}>
            <CheckCircleIcon fontSize="small" sx={{ color: 'primary.main' }} />
          </ConditionalComponent>
        </MenuItem>

        <MenuItem
          onClick={() => handleThemeChange('default')}
          sx={{
            borderRadius: 1,
            py: 1.5,
            display: 'flex',
            justifyContent: 'space-between',
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <SettingsIcon fontSize="small" sx={{ mr: 2, color: 'text.primary' }} />
            <Typography variant="body2">Par défaut</Typography>
          </Box>

          <ConditionalComponent isValid={theme === 'default'} defaultComponent={null}>
            <CheckCircleIcon fontSize="small" sx={{ color: 'primary.main' }} />
          </ConditionalComponent>
        </MenuItem>
      </Menu>
    </>
  );
}
