import React, { useState } from 'react';
import styled from 'styled-components';
import { useNavigate } from 'react-router-dom';
import {
  HiMenu,
  HiMoon,
  HiSun,
  HiChevronDown,
  HiUser,
  HiCog,
  HiLogout,
} from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { useTheme } from '@/app/providers/ThemeProvider';
import { useAuthStore } from '@/features/auth/store/authStore';
import { authService } from '@/features/auth/services/authService';
import { ROUTES } from '@/shared/constants/routes';
import { ROUTE_PERMISSIONS } from '@/shared/config/routePermissions';
import { usePermissions } from '@/features/auth/hooks/usePermissions';
import { IconButton } from '@/shared/components/ui';
import { NotificationBell } from '@/features/notifications/components/NotificationBell';
import { GlobalSearchTrigger } from './GlobalSearchTrigger';
import { useSidebarNav } from '../SidebarNavContext';

const HeaderContainer = styled.header`
  flex-shrink: 0;
  height: ${({ theme }) => theme.layout.headerHeight};
  background-color: ${({ theme }) => theme.colors.surface};
  border-bottom: 1px solid ${({ theme }) => theme.colors.borderSoft};
  box-shadow: ${({ theme }) => theme.shadows.xs};
  z-index: 20;
  backdrop-filter: blur(10px);
`;

const HeaderInner = styled.div`
  display: grid;
  grid-template-columns: 1fr minmax(0, 520px) 1fr;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[4]};
  width: 100%;
  height: ${({ theme }) => theme.layout.headerHeight};
  padding: 0 ${({ theme }) => theme.layout.pagePadding};
  box-sizing: border-box;

  @media (max-width: 768px) {
    grid-template-columns: auto 1fr auto;
    padding: 0 ${({ theme }) => theme.spacing[4]};
  }
`;

const HeaderLeading = styled.div`
  display: flex;
  align-items: center;
  justify-content: flex-start;
  min-width: 0;
`;

const SearchSection = styled.div`
  grid-column: 2;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 0;
  width: 100%;

  @media (max-width: 768px) {
    display: none;
  }
`;

const RightSection = styled.div`
  grid-column: 3;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: ${({ theme }) => theme.spacing[2]};
  flex-shrink: 0;
  min-width: 0;
`;

const UserMenu = styled.div`
  position: relative;
`;

const UserButton = styled.button`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  height: 40px;
  padding: ${({ theme }) => `0 ${theme.spacing[3]} 0 ${theme.spacing[2]}`};
  border-radius: ${({ theme }) => theme.borderRadius.full};
  background-color: ${({ theme }) => theme.colors.surfaceMuted};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
  cursor: pointer;
  transition:
    border-color ${({ theme }) => theme.transitions.fast},
    box-shadow ${({ theme }) => theme.transitions.fast},
    background-color ${({ theme }) => theme.transitions.fast};

  &:hover {
    border-color: ${({ theme }) => theme.colors.border};
    box-shadow: ${({ theme }) => theme.shadows.xs};
    background-color: ${({ theme }) => theme.colors.surface};
  }

  &:focus-visible {
    outline: 2px solid ${({ theme }) => theme.colors.primary};
    outline-offset: 2px;
  }
`;

const Avatar = styled.div`
  width: 32px;
  height: 32px;
  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.xs};
  box-shadow: 0 0 0 2px ${({ theme }) => theme.colors.surface},
    0 0 0 3px ${({ theme }) => theme.colors.primary}33;
`;

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

  @media (max-width: 900px) {
    display: none;
  }
`;

const ChevronIcon = styled(HiChevronDown)`
  width: 14px;
  height: 14px;
  color: ${({ theme }) => theme.colors.text.tertiary};
  flex-shrink: 0;
`;

const Dropdown = styled.div<{ $isOpen: boolean }>`
  position: absolute;
  top: calc(100% + 8px);
  inset-inline-end: 0;
  min-width: 220px;
  background-color: ${({ theme }) => theme.colors.surfaceElevated};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  box-shadow: ${({ theme }) => theme.shadows.lg};
  display: ${({ $isOpen }) => ($isOpen ? 'block' : 'none')};
  z-index: ${({ theme }) => theme.zIndex.dropdown};
  padding: ${({ theme }) => theme.spacing[2]};
  overflow: hidden;
  animation: headerDropdownIn 0.18s cubic-bezier(0.25, 0.1, 0.25, 1);

  @keyframes headerDropdownIn {
    from {
      opacity: 0;
      transform: translateY(-4px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
`;

const DropdownItem = styled.button`
  width: 100%;
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[3]};
  padding: ${({ theme }) => `${theme.spacing[3]} ${theme.spacing[3]}`};
  text-align: start;
  background: none;
  border: none;
  border-radius: ${({ theme }) => theme.borderRadius.md};
  color: ${({ theme }) => theme.colors.text.primary};
  cursor: pointer;
  transition: background-color ${({ theme }) => theme.transitions.fast};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};

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

  svg {
    width: 18px;
    height: 18px;
    flex-shrink: 0;
    color: ${({ theme }) => theme.colors.text.secondary};
  }
`;

const Divider = styled.div`
  height: 1px;
  background-color: ${({ theme }) => theme.colors.borderSoft};
  margin: ${({ theme }) => `${theme.spacing[2]} ${theme.spacing[2]}`};
`;

export const Header: React.FC = () => {
  const navigate = useNavigate();
  const sidebarNav = useSidebarNav();
  const { t, locale, setLocale } = useLocale();
  const { mode, toggleTheme } = useTheme();
  const { user, logout } = useAuthStore();
  const { can } = usePermissions();
  const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);

  const settingsRoute =
    ROUTE_PERMISSIONS[ROUTES.SETTINGS]?.permission &&
    can(ROUTE_PERMISSIONS[ROUTES.SETTINGS]?.permission)
      ? ROUTES.SETTINGS
      : ROUTES.NOTIFICATION_PREFERENCES;

  const closeUserMenu = () => setIsUserMenuOpen(false);

  const handleLogout = async () => {
    try {
      await authService.logout();
    } catch {
      // Clear local session even if the API call fails.
    }
    logout();
    navigate(ROUTES.LOGIN);
  };

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

  return (
    <HeaderContainer>
      <HeaderInner>
        <HeaderLeading>
          {sidebarNav?.isMobile && (
            <IconButton
              size="md"
              label={t('common:navigation.openMenu')}
              aria-expanded={sidebarNav.isDrawerOpen}
              onClick={sidebarNav.toggleDrawer}
            >
              <HiMenu aria-hidden />
            </IconButton>
          )}
        </HeaderLeading>

        <SearchSection>
          <GlobalSearchTrigger />
        </SearchSection>

        <RightSection>
          <IconButton label={t('common:theme.toggle')} onClick={toggleTheme}>
            {mode === 'light' ? <HiMoon aria-hidden /> : <HiSun aria-hidden />}
          </IconButton>

          <IconButton
            label={t('common:language.switch')}
            onClick={() => setLocale(locale === 'en' ? 'ar' : 'en')}
          >
            <span aria-hidden style={{ fontSize: '0.8125rem', fontWeight: 600 }}>
              {locale === 'en' ? 'ع' : 'EN'}
            </span>
          </IconButton>

          <NotificationBell />

          {user && (
            <UserMenu>
              <UserButton
                type="button"
                data-testid="header-user-menu"
                onClick={() => setIsUserMenuOpen(!isUserMenuOpen)}
                aria-expanded={isUserMenuOpen}
                aria-haspopup="menu"
              >
                <Avatar>{getInitials(user.name)}</Avatar>
                <UserName>{user.name}</UserName>
                <ChevronIcon aria-hidden />
              </UserButton>

              <Dropdown $isOpen={isUserMenuOpen}>
                <DropdownItem
                  onClick={() => {
                    closeUserMenu();
                    navigate(ROUTES.PROFILE);
                  }}
                >
                  <HiUser aria-hidden />
                  {t('common:navigation.profile')}
                </DropdownItem>
                <DropdownItem
                  onClick={() => {
                    closeUserMenu();
                    navigate(settingsRoute);
                  }}
                >
                  <HiCog aria-hidden />
                  {t('common:navigation.settings')}
                </DropdownItem>
                <Divider />
                <DropdownItem data-testid="header-logout" onClick={handleLogout}>
                  <HiLogout aria-hidden />
                  {t('common:navigation.logout')}
                </DropdownItem>
              </Dropdown>
            </UserMenu>
          )}
        </RightSection>
      </HeaderInner>
    </HeaderContainer>
  );
};
