'use client';

import React, { useEffect } from 'react';
import Box from '@mui/material/Box';
import Drawer from '@mui/material/Drawer';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import LogoutIcon from '@mui/icons-material/Logout';
import { styled, useTheme, Theme, CSSObject } from '@mui/material/styles';
import { useAuthStore } from '../../login/store/useAuthStore';
import { useAuth } from '../../login/hooks/useAuth';
import Avatar from '@mui/material/Avatar';
import Typography from '@mui/material/Typography';
import Tooltip from '@mui/material/Tooltip';
import useMediaQuery from '@mui/material/useMediaQuery';
import SidebarItems from './SidebarItems';
import { Scrollbar } from '@/shared/components';
import { useCustomizerStore } from '../store/useCustomizerStore';

// Mixins para transições
const openedMixin = (theme: Theme, width: number): CSSObject => ({
  width,
  transition: theme.transitions.create('width', {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.enteringScreen,
  }),
  overflowX: 'hidden',
});

const closedMixin = (theme: Theme, width: number): CSSObject => ({
  transition: theme.transitions.create('width', {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  overflowX: 'hidden',
  width,
});

interface StyledDrawerProps {
  isCollapsed?: boolean;
  isMobile?: boolean;
}

const StyledDrawer = styled(Drawer, {
  shouldForwardProp: (prop) =>
    prop !== 'isCollapsed' &&
    prop !== 'isMobile' &&
    prop !== 'sidebarWidth' &&
    prop !== 'miniSidebarWidth',
})<StyledDrawerProps & { sidebarWidth?: number; miniSidebarWidth?: number }>(({
  theme,
  isCollapsed,
  isMobile,
  sidebarWidth = 270,
  miniSidebarWidth = 87,
}) => {
  const desktopWidth = isCollapsed ? miniSidebarWidth : sidebarWidth;
  const drawerWidth = isMobile ? sidebarWidth : desktopWidth;

  return {
    width: drawerWidth,
    flexShrink: 0,
    whiteSpace: 'nowrap',
    boxSizing: 'border-box',
    ...(isMobile && {
      '& .MuiDrawer-paper': {
        width: sidebarWidth,
        boxSizing: 'border-box',
      },
    }),
    ...(!isMobile && {
      '& .MuiDrawer-paper': {
        ...(isCollapsed
          ? closedMixin(theme, miniSidebarWidth)
          : openedMixin(theme, sidebarWidth)),
        boxSizing: 'border-box',
      },
    }),
  };
});

interface DrawerHeaderProps {
  isCollapsed?: boolean;
}

const DrawerHeader = styled(Box, {
  shouldForwardProp: (prop) => prop !== 'isCollapsed',
})<DrawerHeaderProps>(({ theme, isCollapsed }) => ({
  display: 'flex',
  alignItems: 'center',
  justifyContent: isCollapsed ? 'center' : 'space-between',
  padding: theme.spacing(0, 1),
  ...theme.mixins.toolbar,
}));

const StyledScrollbarContainer = styled(Box)(() => ({
  height: 'calc(100% - 190px)',
}));

const StyledProfileContainer = styled(Box)(({ theme }) => ({
  padding: theme.spacing(2),
}));

interface StyledProfileBoxProps {
  isCollapsed?: boolean;
}

const StyledProfileBox = styled(Box, {
  shouldForwardProp: (prop) => prop !== 'isCollapsed',
})<StyledProfileBoxProps>(({ isCollapsed }) => ({
  display: 'flex',
  alignItems: 'center',
  gap: 16,
  marginBottom: 16,
  flexDirection: 'row',
  justifyContent: isCollapsed ? 'center' : 'flex-start',
}));

const StyledAvatar = styled(Avatar)(({ theme }) => ({
  backgroundColor: theme.palette.primary.main,
}));

const StyledLogoutButton = styled(IconButton)(({ theme }) => ({
  color: theme.palette.text.secondary,
  '&:hover': {
    color: theme.palette.error.main,
    backgroundColor: theme.palette.error.light,
  },
}));

interface StyledBrandTypographyProps {
  isCollapsed?: boolean;
}

const StyledBrandTypography = styled(Typography, {
  shouldForwardProp: (prop) => prop !== 'isCollapsed',
})<StyledBrandTypographyProps>(({ theme, isCollapsed }) => ({
  fontWeight: 700,
  color: theme.palette.mode === 'dark' ? theme.palette.text.primary : '#1a1a1a',
  opacity: isCollapsed ? 0 : 1,
  transition: 'opacity 0.2s ease-in-out',
}));

interface StyledProfileInfoProps {
  isCollapsed?: boolean;
}

const StyledProfileInfo = styled(Box, {
  shouldForwardProp: (prop) => prop !== 'isCollapsed',
})<StyledProfileInfoProps>(({ isCollapsed }) => ({
  flexGrow: 1,
  minWidth: 0,
  opacity: isCollapsed ? 0 : 1,
  transition: 'opacity 0.2s ease-in-out',
}));

export default function Sidebar() {
  const theme = useTheme();
  const {
    isCollapse,
    toggleSidebar,
    isMobileSidebar,
    toggleMobileSidebar,
    isHydrated,
    sidebarWidth,
    miniSidebarWidth,
  } = useCustomizerStore();
  const user = useAuthStore((s) => s.user);
  const { logout } = useAuth();
  const lgUp = useMediaQuery(theme.breakpoints.up('lg'));

  // Fechar sidebar mobile quando redimensionar para desktop
  useEffect(() => {
    if (lgUp && isMobileSidebar) {
      toggleMobileSidebar();
    }
  }, [lgUp, isMobileSidebar, toggleMobileSidebar]);

  // Aguardar hidratação antes de renderizar
  if (!isHydrated) {
    return null;
  }

  const handleMobileClose = () => {
    if (isMobileSidebar) {
      toggleMobileSidebar();
    }
  };

  const handleItemClick = () => {
    if (!lgUp && isMobileSidebar) {
      toggleMobileSidebar();
    }
  };

  return (
    <StyledDrawer
      variant={lgUp ? 'permanent' : 'temporary'}
      open={lgUp ? true : isMobileSidebar}
      onClose={handleMobileClose}
      isCollapsed={isCollapse}
      isMobile={!lgUp}
      sidebarWidth={sidebarWidth}
      miniSidebarWidth={miniSidebarWidth}
      ModalProps={{
        keepMounted: true, // Melhor performance no mobile
      }}
    >
      <DrawerHeader isCollapsed={isCollapse}>
        <StyledBrandTypography variant="h6" noWrap isCollapsed={isCollapse}>
          Jurunense
        </StyledBrandTypography>
        {lgUp ? (
          <IconButton onClick={toggleSidebar}>
            {isCollapse ? <ChevronRightIcon /> : <ChevronLeftIcon />}
          </IconButton>
        ) : (
          <IconButton onClick={handleMobileClose}>
            <ChevronLeftIcon />
          </IconButton>
        )}
      </DrawerHeader>
      <Divider />

      <StyledScrollbarContainer>
        <Scrollbar sx={{ height: '100%' }}>
          <SidebarItems
            open={!isCollapse || !lgUp}
            onItemClick={handleItemClick}
          />
        </Scrollbar>
      </StyledScrollbarContainer>

      <Divider />

      <StyledProfileContainer>
        <StyledProfileBox isCollapsed={isCollapse && lgUp}>
          <Tooltip
            title={
              isCollapse && lgUp
                ? user?.nome || user?.userName || 'Usuário'
                : ''
            }
            placement="right"
          >
            <StyledAvatar>
              {user?.nome?.[0] || user?.userName?.[0] || 'U'}
            </StyledAvatar>
          </Tooltip>
          <StyledProfileInfo isCollapsed={isCollapse && lgUp}>
            <Typography
              variant="body2"
              noWrap
              fontWeight={600}
              sx={{
                color: (theme) =>
                  theme.palette.mode === 'dark'
                    ? theme.palette.text.primary
                    : '#1a1a1a',
              }}
            >
              {user?.nome || user?.userName || 'Usuário'}
            </Typography>
            <Typography
              variant="caption"
              noWrap
              sx={{
                color: (theme) =>
                  theme.palette.mode === 'dark'
                    ? theme.palette.text.secondary
                    : '#4a5568',
              }}
            >
              {user?.nomeFilial || 'Usuário'}
            </Typography>
          </StyledProfileInfo>
        </StyledProfileBox>
        <Tooltip title="Sair" placement="right">
          <StyledLogoutButton onClick={logout} size="small">
            <LogoutIcon />
          </StyledLogoutButton>
        </Tooltip>
      </StyledProfileContainer>
    </StyledDrawer>
  );
}
