'use client';

import * as React from 'react';
import RouterLink from 'next/link';
import { usePathname } from 'next/navigation';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Collapse from '@mui/material/Collapse';
import Divider from '@mui/material/Divider';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { useTheme } from '@mui/material/styles';
import { ArrowSquareUpRight as ArrowSquareUpRightIcon } from '@phosphor-icons/react/dist/ssr/ArrowSquareUpRight';
import { CaretUpDown as CaretUpDownIcon } from '@phosphor-icons/react/dist/ssr/CaretUpDown';

import type { NavItemConfig } from '@/types/nav';
import { paths } from '@/paths';
import { isNavItemActive, isNavGroupActive } from '@/lib/is-nav-item-active';
import {
  isNavGroupHrefActive,
  isNavHrefActive,
  useDashboardNavigation,
} from '@/components/dashboard/layout/navigation-context';
import { DynamicLogo } from '@/components/core/logo';
import { useRouter } from "next/navigation";
import { navItems } from './config';
import { navIcons } from './nav-icons';
import { CaretDown as CaretDownIcon } from '@phosphor-icons/react/dist/ssr/CaretDown';
import { SignOut } from '@phosphor-icons/react';

export function SideNav(): React.JSX.Element {
  const pathname = usePathname();
  const theme = useTheme();
  const router = useRouter();

  const handleLogout = async () => {

    localStorage.removeItem("token");
    localStorage.removeItem("AdminId");

    router.push("/auth/sign-in");
};

  return (
    <Box
      sx={{
        '--SideNav-background': theme.palette.mode === 'dark' 
          ? 'linear-gradient(180deg, #0a0e27 0%, #1a1f3a 100%)' 
          : 'linear-gradient(180deg, #f8fafc 0%, #e2e8f0 100%)',
        '--SideNav-color': theme.palette.mode === 'dark' ? '#e2e8f0' : '#1e293b',
        '--NavItem-color': theme.palette.mode === 'dark' ? '#cbd5e1' : '#475569',
        '--NavItem-hover-background': theme.palette.mode === 'dark' 
          ? 'rgba(59, 130, 246, 0.15)' 
          : 'rgba(59, 130, 246, 0.08)',
        '--NavItem-active-background': theme.palette.mode === 'dark'
          ? 'linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%)'
          : 'linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%)',
        '--NavItem-active-color': theme.palette.mode === 'dark' ? '#ffffff' : '#1e40af',
        '--NavItem-disabled-color': theme.palette.mode === 'dark' ? '#64748b' : '#94a3b8',
        '--NavItem-icon-color': theme.palette.mode === 'dark' ? '#94a3b8' : '#64748b',
        '--NavItem-icon-active-color': theme.palette.mode === 'dark' ? '#ffffff' : '#1e40af',
        '--NavItem-icon-disabled-color': theme.palette.mode === 'dark' ? '#475569' : '#cbd5e1',
        background: 'var(--SideNav-background)',
        color: 'var(--SideNav-color)',
        display: { xs: 'none', lg: 'flex' },
        flexDirection: 'column',
        height: '100vh',
        left: 0,
        maxWidth: '100%',
        position: 'fixed',
        overflowY: 'auto',
        top: 0,
        width: 'var(--SideNav-width)',
        zIndex: 'var(--SideNav-zIndex)',
        boxShadow: theme.palette.mode === 'dark' 
          ? '4px 0 24px rgba(0, 0, 0, 0.4)' 
          : '4px 0 24px rgba(15, 23, 42, 0.08)',
      }}
    >
      <Stack spacing={2} sx={{ p: 3 }}>
        <Box component={RouterLink} href={paths.home} sx={{ 
          display: 'flex',        
          justifyContent: 'center', 
          alignItems: 'center',     
          height: '100%',           
          width: '100%',
          transition: 'all 0.3s ease',
          borderRadius: '12px',
          '&:hover': {
            transform: 'scale(1.05)',
            filter: 'brightness(1.1)',
          }
        }}>
          <DynamicLogo colorLight="dark" colorDark="light" height={122} width={122} />
        </Box>
      </Stack>
      <Divider sx={{ 
        borderColor: theme.palette.mode === 'dark' ? 'rgba(203, 213, 225, 0.15)' : 'rgba(71, 85, 105, 0.15)',
        mx: 2,
        background: theme.palette.mode === 'dark' 
          ? 'linear-gradient(90deg, transparent 0%, rgba(203, 213, 225, 0.15) 50%, transparent 100%)'
          : 'linear-gradient(90deg, transparent 0%, rgba(71, 85, 105, 0.15) 50%, transparent 100%)'
      }} />
      <Box component="nav" sx={{ flex: '1 1 auto', p: '12px' }}>
        {renderNavItems({ pathname, items: navItems })}
      </Box>
      <Divider sx={{ 
        borderColor: theme.palette.mode === 'dark' ? 'rgba(203, 213, 225, 0.15)' : 'rgba(71, 85, 105, 0.15)',
        mx: 2,
        background: theme.palette.mode === 'dark' 
          ? 'linear-gradient(90deg, transparent 0%, rgba(203, 213, 225, 0.15) 50%, transparent 100%)'
          : 'linear-gradient(90deg, transparent 0%, rgba(71, 85, 105, 0.15) 50%, transparent 100%)'
      }} />
      <Stack spacing={2} sx={{ p: '12px' }}>
        <Button
          component="a"
          endIcon={<SignOut size={22} weight="fill" />}
          fullWidth
          sx={{
            background: theme.palette.mode === 'dark' 
              ? 'linear-gradient(135deg, #dc2626 0%, #b91c1c 100%)' 
              : 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)',
            color: '#ffffff',
            borderRadius: '14px',
            border: `2px solid ${theme.palette.mode === 'dark' ? '#dc2626' : '#ef4444'}`,
            fontWeight: '600',
            fontSize: '0.9rem',
            textTransform: 'none',
            py: 1.2,
            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
            position: 'relative',
            overflow: 'hidden',
            '&::before': {
              content: '""',
              position: 'absolute',
              top: 0,
              left: '-100%',
              width: '100%',
              height: '100%',
              background: theme.palette.mode === 'dark'
                ? 'linear-gradient(135deg, #f87171 0%, #ef4444 100%)'
                : 'linear-gradient(135deg, #fca5a5 0%, #f87171 100%)',
              transition: 'left 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
              zIndex: 0,
            },
            '&:hover': {
              transform: 'translateY(-2px)',
              boxShadow: theme.palette.mode === 'dark' 
                ? '0 8px 25px rgba(220, 38, 38, 0.4)' 
                : '0 8px 25px rgba(239, 68, 68, 0.4)',
              '&::before': {
                left: 0,
              },
              '& .MuiButton-endIcon, & .logout-text': {
                color: theme.palette.mode === 'dark' ? '#1f2937' : '#ffffff',
                zIndex: 1,
                position: 'relative',
              }
            },
            '& .MuiButton-endIcon': {
              transition: 'color 0.3s ease',
              zIndex: 1,
              position: 'relative',
            }
          }}
          target="_blank"
          variant="contained"
          onClick={handleLogout}
        >
          <span className="logout-text" style={{ zIndex: 1, position: 'relative' }}>
            Logout
          </span>
        </Button>
      </Stack>
    </Box>
  );
}

function renderNavItems({ items = [], pathname }: { items?: NavItemConfig[]; pathname: string }): React.JSX.Element {
  const children = items.reduce((acc: React.ReactNode[], curr: NavItemConfig): React.ReactNode[] => {
    const { key, ...item } = curr;

    acc.push(<NavItem key={key} pathname={pathname} {...item} />);

    return acc;
  }, []);

  return (
    <Stack component="ul" spacing={1} sx={{ listStyle: 'none', m: 0, p: 0 }}>
      {children}
    </Stack>
  );
}

interface NavItemProps extends NavItemConfig {
  pathname: string;
  depth?: number;
}

function NavItem({
  disabled,
  external,
  href,
  icon,
  matcher,
  pathname,
  title,
  items,
  depth = 0,
}: NavItemProps): React.JSX.Element {
  const theme = useTheme();
  const { pendingHref, startNavigation } = useDashboardNavigation();
  const hasChildren = Boolean(items?.length);
  const groupItem = { disabled, external, href, matcher, title, items };
  const active = hasChildren
    ? isNavGroupHrefActive(groupItem, pathname, pendingHref) ||
      (!pendingHref && isNavGroupActive(groupItem, pathname))
    : isNavHrefActive(href, pathname, pendingHref) ||
      (!pendingHref && isNavItemActive({ disabled, external, href, matcher, pathname }));
  const Icon = icon && depth === 0 ? navIcons[icon] : null;
  const isChildItem = depth > 0;
  const [open, setOpen] = React.useState(active);

  React.useEffect(() => {
    if (active && hasChildren) {
      setOpen(true);
    }
  }, [active, hasChildren]);

  if (hasChildren) {
    return (
      <li>
        <Box
          onClick={() => setOpen((prev) => !prev)}
          role="button"
          aria-expanded={open}
          sx={{
            alignItems: 'center',
            borderRadius: '12px',
            color: active ? 'var(--NavItem-active-color)' : 'var(--NavItem-color)',
            cursor: 'pointer',
            display: 'flex',
            gap: 1.5,
            p: '10px 16px',
            fontWeight: active ? 600 : 500,
            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
            '&:hover': {
              bgcolor: 'var(--NavItem-hover-background)',
            },
            ...(active && {
              background: 'var(--NavItem-active-background)',
              boxShadow: theme.palette.mode === 'dark'
                ? '0 4px 12px rgba(59, 130, 246, 0.3)'
                : '0 4px 12px rgba(59, 130, 246, 0.2)',
            }),
          }}
        >
          <Box sx={{ alignItems: 'center', display: 'flex', justifyContent: 'center', flex: '0 0 auto' }}>
            {Icon ? (
              <Icon
                fill={active ? 'var(--NavItem-icon-active-color)' : 'var(--NavItem-icon-color)'}
                fontSize="var(--icon-fontSize-md)"
                weight={active ? 'fill' : undefined}
              />
            ) : null}
          </Box>
          <Typography
            component="span"
            sx={{
              color: 'inherit',
              fontSize: '0.9rem',
              fontWeight: 'inherit',
              lineHeight: '24px',
              letterSpacing: '0.02em',
              flex: '1 1 auto',
            }}
          >
            {title}
          </Typography>
          <CaretDownIcon
            fontSize="var(--icon-fontSize-sm)"
            style={{
              flexShrink: 0,
              transform: open ? 'rotate(0deg)' : 'rotate(-90deg)',
              transition: 'transform 0.2s ease',
            }}
          />
        </Box>
        <Collapse in={open} timeout="auto" unmountOnExit>
          <Stack component="ul" spacing={0.5} sx={{ listStyle: 'none', m: 0, p: 0, pl: 1.5, mt: 0.5 }}>
            {items?.map(({ key, ...item }) => (
              <NavItem key={key} pathname={pathname} {...item} depth={depth + 1} />
            ))}
          </Stack>
        </Collapse>
      </li>
    );
  }

  return (
    <li>
      <Box
        {...(href
          ? {
              component: external ? 'a' : RouterLink,
              href,
              prefetch: !external,
              target: external ? '_blank' : undefined,
              rel: external ? 'noreferrer' : undefined,
              onClick: () => {
                if (!external && href) {
                  startNavigation(href);
                }
              },
            }
          : { role: 'button' })}
        sx={{
          alignItems: 'center',
          borderRadius: isChildItem ? '10px' : '12px',
          color: 'var(--NavItem-color)',
          cursor: 'pointer',
          display: 'flex',
          flex: '0 0 auto',
          gap: isChildItem ? 1 : 1.5,
          p: isChildItem ? '8px 12px 8px 20px' : '10px 16px',
          position: 'relative',
          textDecoration: 'none',
          whiteSpace: 'nowrap',
          transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
          '&:hover': {
            bgcolor: 'var(--NavItem-hover-background)',
            transform: isChildItem ? 'translateX(2px)' : 'translateX(4px)',
            '&::before': {
              opacity: 1,
              transform: 'scaleX(1)',
            }
          },
          '&::before': {
            content: '""',
            position: 'absolute',
            left: 0,
            top: '50%',
            transform: 'translateY(-50%) scaleX(0)',
            width: '4px',
            height: '60%',
            backgroundColor: theme.palette.mode === 'dark' ? '#3b82f6' : '#2563eb',
            borderRadius: '0 3px 3px 0',
            opacity: 0,
            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
            transformOrigin: 'left center',
          },
          ...(disabled && {
            bgcolor: 'var(--NavItem-disabled-background)',
            color: 'var(--NavItem-disabled-color)',
            cursor: 'not-allowed',
            '&:hover': {
              transform: 'none',
            }
          }),
          ...(active && { 
            background: 'var(--NavItem-active-background)', 
            color: 'var(--NavItem-active-color)',
            fontWeight: '600',
            boxShadow: theme.palette.mode === 'dark' 
              ? '0 4px 12px rgba(59, 130, 246, 0.3)' 
              : '0 4px 12px rgba(59, 130, 246, 0.2)',
            '&::before': {
              opacity: 1,
              transform: 'translateY(-50%) scaleX(1)',
              backgroundColor: theme.palette.mode === 'dark' ? '#ffffff' : '#1e40af',
            }
          }),
        }}
      >
        {!isChildItem && (
          <Box sx={{ alignItems: 'center', display: 'flex', justifyContent: 'center', flex: '0 0 auto' }}>
            {Icon ? (
              <Icon
                fill={active ? 'var(--NavItem-icon-active-color)' : 'var(--NavItem-icon-color)'}
                fontSize="var(--icon-fontSize-md)"
                weight={active ? 'fill' : undefined}
              />
            ) : null}
          </Box>
        )}
        <Box sx={{ flex: '1 1 auto' }}>
          <Typography
            component="span"
            sx={{ 
              color: 'inherit', 
              fontSize: isChildItem ? '0.85rem' : '0.9rem', 
              fontWeight: 'inherit', 
              lineHeight: '24px',
              letterSpacing: '0.02em',
            }}
          >
            {title}
          </Typography>
        </Box>
      </Box>
    </li>
  );
}
