import React, { useContext } from 'react';
import {
  Drawer,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Typography,
  Box,
  Avatar,
  Divider,
  Button,
  styled,
  ListItemButton,
  IconButton,
  Tooltip,
  ListSubheader
} from '@mui/material';
import {
  Home as HomeIcon,
  Info as InfoIcon,
  BugReport as BugReportIcon,
  Article as ArticleIcon,
  Feedback as FeedbackIcon,
  ContactMail as ContactMailIcon,
  ExitToApp as LogoutIcon,
  Login as LoginIcon,
  History as HistoryIcon,
  Brightness4 as DarkModeIcon,
  Brightness7 as LightModeIcon,
  Chat as ChatIcon,
  MenuBook as DocsIcon,
  Speed as SpeedIcon
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { ColorModeContext } from '../../App';

const drawerWidth = 240;

const StyledDrawer = styled(Drawer)({
  width: drawerWidth,
  flexShrink: 0,
  '& .MuiDrawer-paper': {
    width: drawerWidth,
    boxSizing: 'border-box',
    backgroundColor: '#1a1a1a',
    color: 'white',
    display: 'flex',
    flexDirection: 'column',
    height: '100%',
    '& .MuiListItemIcon-root': {
      color: 'white',
      minWidth: '40px'
    },
    '& .MuiDivider-root': {
      borderColor: 'rgba(255, 255, 255, 0.12)',
    },
  },
});

const UserProfile = styled(Box)(({ theme }) => ({
  padding: theme.spacing(2),
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  textAlign: 'center',
  color: 'white'
}));

const WhiteButton = styled(Button)({
  color: 'white',
  borderColor: 'white',
  '&:hover': {
    borderColor: 'rgba(255, 255, 255, 0.8)',
    backgroundColor: 'rgba(255, 255, 255, 0.08)',
  },
});

const WhiteTypography = styled(Typography)({
  color: 'white',
});

const Sidebar: React.FC = () => {
  const navigate = useNavigate();
  const { currentUser, logout } = useAuth();
  const colorMode = useContext(ColorModeContext);

  const handleLogout = async () => {
    try {
      await logout();
      navigate('/login');
    } catch (error) {
      console.error('Error al cerrar sesión:', error);
    }
  };

  const menuItems = {
    myAccount: [
      { text: 'Fast Monitoring', icon: <SpeedIcon />, path: '/fast-monitoring', showWhenLoggedIn: true, isPublic: false },
      { text: 'Varrometer', icon: <HomeIcon />, path: '/varrometer', showWhenLoggedIn: true, isPublic: false },
      { text: 'My History', icon: <HistoryIcon />, path: '/history', showWhenLoggedIn: true, isPublic: false },
      { text: 'Feedback', icon: <ChatIcon />, path: '/feedback', showWhenLoggedIn: true, isPublic: false },
      // NOTA IMPORTANTE: Botón de documentación temporalmente oculto - Descomentar cuando sea necesario en el futuro
      // { text: 'Documentation', icon: <DocsIcon />, path: '/docs', showWhenLoggedIn: true, isPublic: false },
      { text: 'Logout', icon: <LogoutIcon />, action: handleLogout, showWhenLoggedIn: true, isPublic: false },
    ],
    general: [
      { text: 'Home', icon: <HomeIcon />, path: '/', showWhenLoggedIn: true, isPublic: true },
      { text: 'About', icon: <InfoIcon />, path: '/about', showWhenLoggedIn: true, isPublic: true },
      { text: 'Discover Varroa', icon: <BugReportIcon />, path: '/discover', showWhenLoggedIn: true, isPublic: true },
      { text: 'News', icon: <ArticleIcon />, path: '/news', showWhenLoggedIn: true, isPublic: true },
      { text: 'Contact', icon: <ContactMailIcon />, path: '/contact', showWhenLoggedIn: true, isPublic: true },
    ]
  };

  return (
    <StyledDrawer variant="permanent" anchor="left">
      <Box sx={{ 
        display: 'flex', 
        flexDirection: 'column',
        alignItems: 'center',
        pt: { xs: 2, sm: 4 }, 
        pb: { xs: 1, sm: 2 },
        borderBottom: '1px solid rgba(255, 255, 255, 0.12)'
      }}>
        {currentUser ? (
          <>
            {console.log('Sidebar Avatar Props:', {
              photoURL: currentUser.photoURL,
              displayName: currentUser.displayName,
              email: currentUser.email
            })}
            <Avatar
              src={currentUser.photoURL || undefined}
              alt={currentUser.displayName || 'User'}
              sx={{ 
                width: { xs: 60, sm: 80 }, 
                height: { xs: 60, sm: 80 }, 
                mb: 1,
                bgcolor: 'primary.main',
                fontSize: { xs: '1.5rem', sm: '2rem' },
                border: '2px solid white',
                '& .MuiAvatar-img': {
                  objectFit: 'cover',
                  width: '100%',
                  height: '100%'
                }
              }}
            >
              {!currentUser.photoURL && (currentUser.displayName?.[0] || currentUser.email?.[0] || 'U').toUpperCase()}
            </Avatar>
          </>
        ) : (
          <Avatar
            src="/images/logovarroa.png"
            sx={{ 
              width: { xs: 60, sm: 80 },
              height: { xs: 60, sm: 80 },
              mb: 1,
              bgcolor: 'white'
            }}
          />
        )}
        {currentUser && (
          <>
            <WhiteTypography variant="h6" gutterBottom sx={{ fontSize: { xs: '1rem', sm: '1.25rem' } }}>
              {currentUser.displayName || currentUser.email}
            </WhiteTypography>
            <WhiteTypography variant="body2" gutterBottom sx={{ fontSize: { xs: '0.75rem', sm: '0.875rem' } }}>
              {currentUser.email}
            </WhiteTypography>
          </>
        )}
      </Box>

      <Divider />

      <Box sx={{ 
        flex: 1, 
        display: 'flex', 
        flexDirection: 'column',
        overflowY: 'auto',  
        '&::-webkit-scrollbar': {
          width: '4px',
        },
        '&::-webkit-scrollbar-track': {
          background: 'rgba(0, 0, 0, 0.1)',
        },
        '&::-webkit-scrollbar-thumb': {
          background: 'rgba(255, 255, 255, 0.3)',
          borderRadius: '2px',
        },
        '&::-webkit-scrollbar-thumb:hover': {
          background: 'rgba(255, 255, 255, 0.5)',
        },
      }}>
        <List sx={{ py: 0 }}>
          {currentUser && (
            <>
              <ListSubheader sx={{ 
                bgcolor: 'transparent', 
                color: 'white', 
                fontWeight: 'bold',
                lineHeight: { xs: '28px', sm: '32px' },
                py: 0
              }}>
                My Account
              </ListSubheader>
              {menuItems.myAccount.map((item) => (
                <ListItem key={item.text} disablePadding>
                  <ListItemButton 
                    onClick={item.action || (() => navigate(item.path))}
                    sx={{
                      minHeight: { xs: '36px', sm: '40px' },
                      py: 0,
                      '&:hover': {
                        backgroundColor: 'rgba(255, 255, 255, 0.08)',
                      },
                    }}
                  >
                    <ListItemIcon sx={{ color: 'white', minWidth: { xs: '32px', sm: '40px' } }}>
                      {item.icon}
                    </ListItemIcon>
                    <ListItemText 
                      primary={item.text} 
                      sx={{ 
                        '& .MuiTypography-root': { 
                          color: 'white',
                          fontSize: { xs: '0.85rem', sm: '1rem' }
                        } 
                      }} 
                    />
                  </ListItemButton>
                </ListItem>
              ))}
              <Divider sx={{ my: 1, bgcolor: 'rgba(255, 255, 255, 0.12)' }} />
            </>
          )}
          
          <ListSubheader sx={{ 
            bgcolor: 'transparent', 
            color: 'white', 
            fontWeight: 'bold',
            lineHeight: { xs: '28px', sm: '32px' },
            py: 0
          }}>
            General
          </ListSubheader>
          {menuItems.general
            .filter(item => currentUser ? item.showWhenLoggedIn : item.isPublic)
            .map((item) => (
              <ListItem key={item.text} disablePadding>
                <ListItemButton 
                  onClick={() => navigate(item.path)}
                  sx={{
                    minHeight: { xs: '36px', sm: '40px' },
                    py: 0,
                    '&:hover': {
                      backgroundColor: 'rgba(255, 255, 255, 0.08)',
                    },
                  }}
                >
                  <ListItemIcon sx={{ color: 'white', minWidth: { xs: '32px', sm: '40px' } }}>
                    {item.icon}
                  </ListItemIcon>
                  <ListItemText 
                    primary={item.text} 
                    sx={{ 
                      '& .MuiTypography-root': { 
                        color: 'white',
                        fontSize: { xs: '0.85rem', sm: '1rem' }
                      } 
                    }} 
                  />
                </ListItemButton>
              </ListItem>
            ))}
        </List>
      </Box>

      <Box sx={{ 
        borderTop: '1px solid rgba(255, 255, 255, 0.12)',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        py: { xs: 0.5, sm: 1 }
      }}>
        {!currentUser && (
          <WhiteButton
            variant="contained"
            startIcon={<LoginIcon />}
            onClick={() => navigate('/login')}
            sx={{
              bgcolor: '#f4811e',
              mb: 1,
              px: 4,
              fontSize: { xs: '0.85rem', sm: '1rem' },
              '&:hover': {
                bgcolor: '#d16c18',
              }
            }}
          >
            Iniciar Sesión
          </WhiteButton>
        )}
        
        {currentUser && (
          <ListItemButton
            onClick={colorMode.toggleColorMode}
            sx={{
              minHeight: { xs: '36px', sm: '40px' },
              py: 0,
              justifyContent: 'center',
              '&:hover': {
                backgroundColor: 'rgba(255, 255, 255, 0.08)',
              },
            }}
          >
            <ListItemIcon sx={{ color: 'white', minWidth: 'auto', mr: 1 }}>
              {colorMode.mode === 'dark' ? <LightModeIcon /> : <DarkModeIcon />}
            </ListItemIcon>
            <ListItemText 
              primary="Dark Mode" 
              sx={{ 
                '& .MuiTypography-root': { 
                  color: 'white',
                  textAlign: 'center',
                  fontSize: { xs: '0.85rem', sm: '1rem' }
                } 
              }} 
            />
          </ListItemButton>
        )}

        <WhiteTypography variant="caption" sx={{ opacity: 0.7, textAlign: 'center', mt: 0.5, fontSize: { xs: '0.7rem', sm: '0.75rem' } }}>
          {new Date().getFullYear()} BeeLife VarrometerApp
        </WhiteTypography>
      </Box>
    </StyledDrawer>
  );
};

export default Sidebar;
