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 { 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 { FeatureHighlight } from '@/components/ui/feature-highlight';
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();
  const { theme, setTheme, sidebarOpen, setSidebarOpen } = useUIStore();
  const { t } = useTranslation();
  const navigate = useNavigate();

  const handleLogout = async () => {
    await logout();
    navigate('/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 className="fixed top-0 left-0 right-0 h-header z-50 pointer-events-none">
      <div className={cn(
        'absolute top-0 right-0 h-header bg-background/80 backdrop-blur-lg border-b border-border/50 flex items-center justify-between px-4 md:px-6 pointer-events-auto transition-all duration-[var(--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-white/5 text-muted-foreground hover:text-foreground mr-2 transition-colors"
        >
          <Menu className="w-5 h-5" />
        </button>

        {/* Search — Spotify-style: subtle, rounded */}
        <FeatureHighlight
          id="header-search"
          title="Quick Search"
          description="Find tracks, playlists, and users instantly. Press Ctrl+K from anywhere to jump here."
          position="bottom"
        >
          <div className="flex-1 max-w-md relative hidden md:block group">
            <div className="relative flex items-center group/search rounded-full focus-within:ring-2 focus-within:ring-primary/50 transition-all">
              <Search className="absolute left-3 w-4 h-4 text-muted-foreground pointer-events-none" />
              <input
                type="text"
                placeholder="What do you want to play?"
                className="w-full h-10 pl-10 pr-4 bg-white/5 border-0 rounded-full text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-0 transition-all"
              />
              <kbd className="absolute right-3 hidden sm:inline-flex items-center gap-0.5 px-2 py-0.5 rounded bg-white/5 text-xs font-medium text-muted-foreground">
                <Command className="w-3 h-3" />K
              </kbd>
            </div>
          </div>
        </FeatureHighlight>

        {/* 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-white/5 text-muted-foreground">
            <span className="w-1.5 h-1.5 rounded-full bg-primary shrink-0" />
            <span className="text-xs">Online</span>
          </div>

          <NotificationMenu />
          <RateLimitIndicator />

          <div className="h-6 w-px bg-white/10 mx-1" />

          <FeatureHighlight
            id="keyboard-shortcuts"
            title="Keyboard Shortcuts"
            description="Press ? anytime to see all available keyboard shortcuts for faster navigation."
            position="bottom"
          >
            <Tooltip content={t('common.changeTheme')}>
              <Button
                variant="ghost"
                size="icon"
                onClick={toggleTheme}
                className="min-h-10 min-w-10 rounded-full hover:bg-white/5 text-muted-foreground hover:text-foreground"
              >
                {getThemeIcon()}
              </Button>
            </Tooltip>
          </FeatureHighlight>

          {/* User — compact pill */}
          <div className="relative">
            <button
              onClick={() => setIsUserMenuOpen(!isUserMenuOpen)}
              className="flex items-center gap-2 pl-0.5 pr-2 py-0.5 rounded-full hover:bg-white/5 transition-colors focus:outline-none focus:ring-2 focus:ring-white/20 group"
            >
              <div className="w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center shrink-0 group-hover:ring-2 group-hover:ring-primary/50 group-hover:scale-105 transition-all">
                <span className="text-xs font-semibold text-primary">
                  {user?.username?.substring(0, 2).toUpperCase() || 'VZ'}
                </span>
              </div>
              <span className="hidden lg:block text-sm font-medium text-foreground truncate max-w-24">
                {user?.username}
              </span>
            </button>

            {isUserMenuOpen && (
              <FocusTrap active={isUserMenuOpen} onEscape={() => setIsUserMenuOpen(false)}>
                <div className="absolute right-0 top-full mt-2 w-56 bg-card backdrop-blur-xl border border-white/10 rounded-xl shadow-xl p-2 z-50 animate-scaleIn origin-top-right">
                  <div className="px-3 py-2.5 border-b border-white/5 mb-1">
                    <p className="text-sm font-semibold text-foreground truncate">{user?.username}</p>
                    <p className="text-xs text-muted-foreground truncate">{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">
                      <User className="w-4 h-4" /> Profil
                    </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">
                      <Settings className="w-4 h-4" /> Paramètres
                    </Link>
                  </div>

                  <div className="h-px bg-white/5 my-1" />

                  <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">
                      <LogOut className="w-4 h-4" /> Déconnexion
                    </button>
                  </div>
                </div>
              </FocusTrap>
            )}
          </div>
        </div>
      </div>
    </header>
  );
}