import React from 'react';
import styled from 'styled-components';
import { NavLink, useNavigate } from 'react-router-dom';
import {
  HiHome,
  HiTicket,
  HiSearch,
  HiUserGroup,
  HiOfficeBuilding,
  HiClipboardList,
  HiShieldCheck,
  HiMail,
  HiViewGrid,
  HiCollection,
  HiAdjustments,
  HiClock,
  HiChartBar,
  HiDocumentText,
  HiDuplicate,
} from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { ROUTES } from '@/shared/constants/routes';
import { AppLogo } from '@/shared/components/layout/AppLogo';
import { ADMIN_NAV_ITEMS, MAIN_NAV_ITEMS } from '@/shared/config/navConfig';
import { useVisibleNavItems } from '@/features/auth/hooks/useVisibleNavItems';
import { usePermissions } from '@/features/auth/hooks/usePermissions';
import { useAuthStore } from '@/features/auth/store/authStore';
import { SIDEBAR_MOBILE_MAX_WIDTH } from '../SidebarNavContext';

interface SidebarProps {
  isCollapsed?: boolean;
}

const SidebarContainer = styled.aside<{ $isCollapsed: boolean }>`
  height: 100dvh;
  width: ${({ theme, $isCollapsed }) =>
    $isCollapsed ? theme.layout.sidebarWidthCollapsed : theme.layout.sidebarWidth};
  min-width: ${({ theme, $isCollapsed }) =>
    $isCollapsed ? theme.layout.sidebarWidthCollapsed : theme.layout.sidebarWidth};
  background-color: ${({ theme }) => theme.colors.surface};
  border-inline-end: 1px solid ${({ theme }) => theme.colors.borderSoft};
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
  z-index: ${({ theme }) => theme.zIndex.sticky};
  transition:
    width ${({ theme }) => theme.transitions.normal},
    min-width ${({ theme }) => theme.transitions.normal};

  @media ${SIDEBAR_MOBILE_MAX_WIDTH} {
    position: fixed;
    inset-inline-start: ${({ $isCollapsed }) => ($isCollapsed ? '-300px' : '0')};
    top: 0;
    bottom: 0;
    width: 300px;
    min-width: 300px;
    z-index: ${({ theme }) => theme.zIndex.fixed + 1};
    box-shadow: ${({ theme, $isCollapsed }) => ($isCollapsed ? 'none' : theme.shadows.xl)};
  }
`;

const SidebarBrand = styled.div`
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: ${({ theme }) => theme.layout.headerHeight};
  padding: 0 ${({ theme }) => theme.spacing[4]};
  border-bottom: 1px solid ${({ theme }) => theme.colors.borderSoft};
  box-sizing: border-box;
`;

const SidebarNavScroll = styled.div`
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  overflow-x: hidden;
`;

const Nav = styled.nav`
  padding: ${({ theme }) => `${theme.spacing[6]} ${theme.spacing[4]}`};
`;

const NavSection = styled.div`
  margin-bottom: ${({ theme }) => theme.spacing[10]};

  &:not(:last-of-type)::after {
    content: '';
    display: block;
    height: 1px;
    margin: ${({ theme }) => `${theme.spacing[8]} ${theme.spacing[4]} 0`};
    background: ${({ theme }) => theme.colors.borderSoft};
  }

  &:last-of-type {
    margin-bottom: ${({ theme }) => theme.spacing[6]};
  }
`;

const NavSectionTitle = styled.h3<{ $isCollapsed: boolean }>`
  font-size: 0.625rem;
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  color: ${({ theme }) => theme.colors.text.tertiary};
  text-transform: uppercase;
  letter-spacing: 0.1em;
  margin: 0 0 ${({ theme }) => theme.spacing[4]};
  padding: 0 ${({ theme }) => theme.spacing[4]};
  opacity: ${({ $isCollapsed }) => ($isCollapsed ? 0 : 1)};
  transition: opacity ${({ theme }) => theme.transitions.fast};
`;

const NavIcon = styled.span`
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 20px;
  color: ${({ theme }) => theme.colors.text.tertiary};
  transition: color ${({ theme }) => theme.transitions.fast};

  svg {
    width: 20px;
    height: 20px;
    stroke-width: 0;
  }
`;

const StyledNavLink = styled(NavLink)<{ $isCollapsed: boolean }>`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[3]};
  padding: 0.625rem ${({ theme }) => theme.spacing[3]};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  color: ${({ theme }) => theme.colors.text.secondary};
  text-decoration: none;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  transition:
    background-color ${({ theme }) => theme.transitions.fast},
    color ${({ theme }) => theme.transitions.fast},
    box-shadow ${({ theme }) => theme.transitions.fast};
  margin-bottom: ${({ theme }) => theme.spacing[1]};
  justify-content: ${({ $isCollapsed }) => ($isCollapsed ? 'center' : 'flex-start')};
  min-height: 40px;

  &:hover {
    background-color: ${({ theme }) => theme.colors.surfaceMuted};
    color: ${({ theme }) => theme.colors.text.primary};
  }

  &.active {
    background-color: ${({ theme }) => theme.colors.primaryLight};
    color: ${({ theme }) => theme.colors.primary};
    font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
    box-shadow:
      inset 0 0 0 1px ${({ theme }) => theme.colors.primary}30,
      0 2px 8px ${({ theme }) => theme.colors.primary}14;

    ${NavIcon} {
      color: ${({ theme }) => theme.colors.primary};
    }
  }
`;

const NavText = styled.span<{ $isCollapsed: boolean }>`
  max-width: ${({ $isCollapsed }) => ($isCollapsed ? 0 : '240px')};
  opacity: ${({ $isCollapsed }) => ($isCollapsed ? 0 : 1)};
  overflow: hidden;
  transition:
    opacity ${({ theme }) => theme.transitions.fast},
    max-width ${({ theme }) => theme.transitions.normal};
  white-space: nowrap;
`;

const SidebarFooter = styled.footer<{ $isCollapsed: boolean }>`
  flex-shrink: 0;
  padding: ${({ theme }) => theme.spacing[4]};
  border-top: 1px solid ${({ theme }) => theme.colors.borderSoft};
  opacity: ${({ $isCollapsed }) => ($isCollapsed ? 0 : 1)};
  pointer-events: ${({ $isCollapsed }) => ($isCollapsed ? 'none' : 'auto')};
  transition: opacity ${({ theme }) => theme.transitions.fast};
`;

const ProfileCard = styled.div`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[3]};
  min-width: 0;
  padding: ${({ theme }) => theme.spacing[3]};
  border-radius: ${({ theme }) => theme.borderRadius.xl};
  background-color: ${({ theme }) => theme.colors.surfaceMuted};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
  box-shadow: ${({ theme }) => theme.shadows.xs};
`;

const ProfileAvatar = styled.div`
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(
    135deg,
    ${({ theme }) => theme.colors.primary} 0%,
    ${({ theme }) => theme.colors.secondary} 100%
  );
  color: ${({ theme }) => theme.colors.text.inverse};
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  flex-shrink: 0;
  box-shadow:
    0 0 0 2px ${({ theme }) => theme.colors.surfaceMuted},
    0 0 0 3px ${({ theme }) => theme.colors.primary}28;
`;

const ProfileText = styled.div`
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
  text-align: start;
`;

const ProfileName = styled.span`
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.primary};
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
`;

const ProfileRole = styled.span`
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  color: ${({ theme }) => theme.colors.text.tertiary};
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
`;

const ICONS: Record<string, React.ReactNode> = {
  dashboard: <HiHome />,
  tickets: <HiTicket />,
  search: <HiSearch />,
  companies: <HiOfficeBuilding />,
  roles: <HiShieldCheck />,
  users: <HiUserGroup />,
  invites: <HiMail />,
  departments: <HiViewGrid />,
  categories: <HiCollection />,
  ticketMeta: <HiAdjustments />,
  templates: <HiDuplicate />,
  sla: <HiClock />,
  assigneePerformance: <HiChartBar />,
  audit: <HiDocumentText />,
};

function iconKeyFromLabelKey(labelKey: string): string {
  const withoutNamespace = labelKey.includes(':') ? labelKey.split(':').slice(1).join(':') : labelKey;
  return withoutNamespace.split('.').pop() ?? 'default';
}

function iconForLabelKey(labelKey: string): React.ReactNode {
  const key = iconKeyFromLabelKey(labelKey);
  return ICONS[key] ?? <HiClipboardList />;
}

function getInitials(name: string): string {
  return name
    .split(' ')
    .map((part) => part[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);
}

export const Sidebar: React.FC<SidebarProps> = ({ isCollapsed = false }) => {
  const navigate = useNavigate();
  const { t } = useLocale();
  const { isReady } = usePermissions();
  const user = useAuthStore((state) => state.user);
  const mainNavItems = useVisibleNavItems(MAIN_NAV_ITEMS);
  const adminNavItems = useVisibleNavItems(ADMIN_NAV_ITEMS);

  const roleLabel =
    user?.roles?.[0]?.display_name ?? user?.roles?.[0]?.name ?? '';

  if (!isReady) {
    return null;
  }

  return (
    <SidebarContainer $isCollapsed={isCollapsed} data-testid="app-sidebar">
      <SidebarBrand>
        <AppLogo onClick={() => navigate(ROUTES.DASHBOARD)} />
      </SidebarBrand>

      <SidebarNavScroll data-testid="sidebar-nav-scroll">
        <Nav>
          <NavSection>
            <NavSectionTitle $isCollapsed={isCollapsed}>
              {t('common:navigation.mainSection')}
            </NavSectionTitle>
            {mainNavItems.map((item) => (
              <StyledNavLink key={item.path} to={item.path} $isCollapsed={isCollapsed}>
                <NavIcon>{iconForLabelKey(item.labelKey)}</NavIcon>
                <NavText $isCollapsed={isCollapsed}>{t(item.labelKey)}</NavText>
              </StyledNavLink>
            ))}
          </NavSection>

          {adminNavItems.length > 0 && (
            <NavSection>
              <NavSectionTitle $isCollapsed={isCollapsed}>
                {t('common:navigation.adminSection')}
              </NavSectionTitle>
              {adminNavItems.map((item) => (
                <StyledNavLink key={item.path} to={item.path} $isCollapsed={isCollapsed}>
                  <NavIcon>{iconForLabelKey(item.labelKey)}</NavIcon>
                  <NavText $isCollapsed={isCollapsed}>{t(item.labelKey)}</NavText>
                </StyledNavLink>
              ))}
            </NavSection>
          )}
        </Nav>
      </SidebarNavScroll>

      {user ? (
        <SidebarFooter $isCollapsed={isCollapsed} data-testid="sidebar-footer">
          <ProfileCard>
            <ProfileAvatar aria-hidden>{getInitials(user.name)}</ProfileAvatar>
            <ProfileText>
              <ProfileName>{user.name}</ProfileName>
              {roleLabel ? <ProfileRole>{roleLabel}</ProfileRole> : null}
            </ProfileText>
          </ProfileCard>
        </SidebarFooter>
      ) : null}
    </SidebarContainer>
  );
};
