import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuthStore } from '@/features/auth/store/authStore';
import { useUser } from '@/features/auth/hooks/useUser';
import { usePresenceSync } from '@/features/presence/hooks/usePresenceSync';
import { useUIStore } from '@/stores/ui';
import { useTranslation } from '@/hooks/useTranslation';
import { EmailVerificationBadge } from '@/features/auth/components/EmailVerificationBadge';
import { NotificationMenu } from '@/components/notifications/NotificationMenu';
import { RateLimitIndicator } from '@/components/RateLimitIndicator';
import { Button } from '@/components/ui/button';
import { FocusTrap } from '@/components/ui/focus-trap';
import { Tooltip } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
import {
  User,
  Settings,
  LogOut,
  Moon,
  Sun,
  Monitor,
  Search,
  Command,
  Menu,
} from 'lucide-react';
import type { BaseComponentProps } from '../types';

export interface HeaderProps extends BaseComponentProps { }

export function Header(_props: HeaderProps) {
  const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
  const { logout } = useAuthStore();
  const { data: user } = useUser();
  usePresenceSync(!!user?.id);
  const { theme, setTheme, sidebarOpen, setSidebarOpen } = useUIStore();
  const { t } = useTranslation();
  const navigate = useNavigate();

  const handleLogout = async () => {
    setIsUserMenuOpen(false);
    await logout();
    // Full page redirect ensures clean state after logout
    window.location.href = '/login';
  };

  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : theme === 'dark' ? 'system' : 'light';
    setTheme(newTheme);
  };

  const getThemeIcon = () => {
    switch (theme) {
      case 'light': return <Sun className="h-4 w-4" />;
      case 'dark': return <Moon className="h-4 w-4" />;
      default: return <Monitor className="h-4 w-4" />;
    }
  };

  return (
    <header data-testid="app-header" className="fixed top-0 left-0 right-0 h-header z-[var(--sumi-z-sticky)] pointer-events-none">
      <div className={cn(
        'absolute top-0 right-0 h-header bg-[var(--sumi-glass-bg)] backdrop-blur-[12px] border-b border-[var(--sumi-border-faint)] flex items-center justify-between px-4 md:px-6 pointer-events-auto transition-all duration-[var(--sumi-duration-fast)]',
        sidebarOpen ? 'left-header-expanded' : 'left-header-collapsed',
        'max-lg:left-0'
      )}>

        {/* Mobile Sidebar Toggle */}
        <button
          onClick={() => setSidebarOpen(!sidebarOpen)}
          className="lg:hidden p-2 rounded-lg hover:bg-muted/50 text-muted-foreground hover:text-foreground mr-2 transition-colors duration-[var(--duration-fast)]"
        >
          <Menu className="w-5 h-5" />
        </button>

        {/* Search — Spotify-style: pill shape, smooth focus expansion */}
        <div className="flex-1 max-w-lg relative hidden md:block">
          <div
            role="search"
            className="relative flex items-center rounded-full transition-all duration-[var(--sumi-duration-normal)] ease-[var(--sumi-ease-out)] group/search"
          >
            <Search className="absolute left-3.5 w-4 h-4 text-muted-foreground pointer-events-none transition-colors duration-[var(--sumi-duration-fast)] group-focus-within/search:text-primary" />
            <input
              data-testid="search-input"
              type="search"
              placeholder={t('header.searchPlaceholder')}
              aria-label={t('header.searchAriaLabel')}
              className={cn(
                'w-full h-10 pl-10 pr-20 rounded-full text-sm text-foreground',
                'bg-[var(--sumi-surface-subtle)] border border-transparent',
                'placeholder:text-muted-foreground/50',
                'focus:outline-none focus:bg-[var(--sumi-surface-card)] focus:border-[var(--sumi-border-accent)] focus:shadow-[var(--sumi-shadow-glow)]',
                'hover:bg-[var(--sumi-bg-hover)]',
                'transition-all duration-[var(--sumi-duration-normal)] ease-[var(--sumi-ease-out)]',
              )}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  const q = (e.currentTarget.value || '').trim();
                  navigate(q ? `/search?q=${encodeURIComponent(q)}` : '/search');
                }
              }}
            />
            <kbd className="absolute right-3 hidden sm:inline-flex items-center gap-1 px-2 py-1 rounded-md bg-[var(--sumi-bg-overlay)] text-[10px] font-mono font-medium text-muted-foreground/70 border border-[var(--sumi-border-faint)]">
              <Command className="w-3 h-3" />K
            </kbd>
          </div>
        </div>

        {/* Right Actions */}
        <div className="flex items-center gap-1 ml-2">

          <div className="hidden xl:flex items-center gap-2 mr-2 px-2.5 py-1 rounded-full bg-muted/30 text-muted-foreground">
            <span className="w-1.5 h-1.5 rounded-full bg-primary shrink-0" />
            <span className="text-xs">{t('header.online')}</span>
          </div>

          <NotificationMenu />
          <RateLimitIndicator />

          <div className="h-6 w-px bg-border mx-1" aria-hidden />

          <Tooltip content={t('common.changeTheme')}>
            <Button
              variant="ghost"
              size="icon"
              onClick={toggleTheme}
              className="min-h-10 min-w-10 rounded-full hover:bg-muted/50 text-muted-foreground hover:text-foreground transition-colors duration-[var(--duration-fast)]"
            >
              {getThemeIcon()}
            </Button>
          </Tooltip>

          {/* User — compact pill (Discord-style) */}
          <div className="relative">
            <button
              data-testid="user-menu"
              onClick={() => setIsUserMenuOpen(!isUserMenuOpen)}
              className="flex items-center gap-2 pl-0.5 pr-2.5 py-0.5 rounded-full hover:bg-[var(--sumi-bg-hover)] transition-all duration-[var(--sumi-duration-normal)] ease-[var(--sumi-ease-out)] focus:outline-none focus:ring-2 focus:ring-ring group"
            >
              <div className="relative w-8 h-8 rounded-full bg-gradient-to-br from-primary/30 to-primary/10 flex items-center justify-center shrink-0 group-hover:ring-2 group-hover:ring-primary/40 group-hover:scale-105 transition-all duration-[var(--sumi-duration-normal)]">
                <span className="text-xs font-bold text-primary">
                  {user?.username?.substring(0, 2).toUpperCase() || 'VZ'}
                </span>
                {/* Online indicator */}
                <span className="absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full bg-[var(--sumi-sage)] border-2 border-[var(--sumi-bg-base)]" aria-hidden="true" />
              </div>
              <span className="hidden lg:block text-sm font-medium text-foreground truncate max-w-28">
                {user?.username}
              </span>
            </button>

            {isUserMenuOpen && (
              <FocusTrap active={isUserMenuOpen} onEscape={() => setIsUserMenuOpen(false)}>
                <div className="absolute right-0 top-full mt-2 w-64 bg-[var(--sumi-surface-elevated)] backdrop-blur-2xl border border-[var(--sumi-glass-border)] rounded-2xl shadow-2xl p-1.5 z-50 animate-scaleIn origin-top-right ring-1 ring-white/5">
                  <div className="px-3 py-3 border-b border-[var(--sumi-border-faint)] mb-1">
                    <p className="text-sm font-semibold text-foreground truncate">{user?.username}</p>
                    <p className="text-xs text-muted-foreground truncate mt-0.5">{user?.email}</p>
                    {!user?.is_verified && (
                      <div className="mt-2 flex justify-center"><EmailVerificationBadge verified={false} /></div>
                    )}
                  </div>

                  <div className="p-1 space-y-0.5">
                    <Link to="/profile" className="flex items-center gap-3 px-3 py-2.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted rounded-xl transition-colors duration-[var(--duration-fast)]">
                      <User className="w-4 h-4" /> {t('header.profile')}
                    </Link>
                    <Link to="/settings" className="flex items-center gap-3 px-3 py-2.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted rounded-xl transition-colors duration-[var(--duration-fast)]">
                      <Settings className="w-4 h-4" /> {t('nav.settings')}
                    </Link>
                  </div>

                  <div className="h-px bg-border my-1" aria-hidden />

                  <div className="p-1">
                    <button onClick={handleLogout} className="w-full flex items-center gap-3 px-3 py-2.5 text-sm text-destructive hover:bg-destructive/10 rounded-xl transition-colors duration-[var(--duration-fast)]">
                      <LogOut className="w-4 h-4" /> {t('header.signOut')}
                    </button>
                  </div>
                </div>
              </FocusTrap>
            )}
          </div>
        </div>
      </div>
    </header>
  );
}