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 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-20 z-50 pointer-events-none">
      <div className={cn(
        "absolute top-0 right-0 h-20 bg-gradient-to-b from-kodo-void/90 via-kodo-void/80 to-transparent backdrop-blur-[8px] flex items-center justify-between px-6 pointer-events-auto transition-all duration-500",
        // Adapter la largeur et la position en fonction de la sidebar
        sidebarOpen ? "left-72" : "left-20",
        // Sur mobile, full width
        "max-lg:left-0"
      )}>

        {/* Mobile Sidebar Toggle */}
        <button
          onClick={() => setSidebarOpen(!sidebarOpen)}
          className="lg:hidden p-2 rounded-lg hover:bg-white/5 text-kodo-text-dim hover:text-white mr-4"
        >
          <Menu className="w-5 h-5" />
        </button>

        {/* Global Search Omnibox */}
        <div className="flex-1 max-w-xl relative hidden md:block group">
          <div className="relative flex items-center group/search">
            <Search className="absolute left-4 w-4 h-4 text-kodo-text-dim group-hover/search:text-kodo-cyan transition-colors duration-300" />
            <input
              type="text"
              placeholder="Search Network..."
              className="w-full h-11 pl-12 pr-16 bg-white/5 border border-white/10 rounded-2xl text-sm text-white placeholder:text-white/30 focus:outline-none focus:bg-kodo-ink/60 focus:border-kodo-cyan/30 focus:ring-4 focus:ring-kodo-cyan/10 transition-all duration-300 shadow-inner"
            />
            <div className="absolute right-3 px-2 py-1 rounded-md bg-white/5 border border-white/5 text-[10px] font-mono font-bold text-kodo-text-dim group-hover/search:text-white group-hover/search:bg-white/10 transition-colors">
              CMD+K
            </div>
          </div>
        </div>

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

          <div className="hidden xl:flex items-center gap-2 mr-4 px-3 py-1.5 rounded-full bg-kodo-cyan/5 border border-kodo-cyan/10">
            <div className="w-1.5 h-1.5 rounded-full bg-kodo-lime animate-pulse shadow-[0_0_8px_rgba(var(--kodo-lime),0.5)]" />
            <span className="text-[10px] font-mono text-kodo-cyan uppercase font-bold tracking-tight">
              Network Stable
            </span>
          </div>

          <NotificationMenu />
          <RateLimitIndicator />

          <div className="h-8 w-px bg-gradient-to-b from-transparent via-white/10 to-transparent mx-2" />

          {/* Theme Toggle */}
          <Tooltip content={t('common.changeTheme')}>
            <Button
              variant="ghost"
              size="icon"
              onClick={toggleTheme}
              className="w-9 h-9 rounded-xl hover:bg-white/5 hover:text-white text-kodo-text-dim"
            >
              {getThemeIcon()}
            </Button>
          </Tooltip>

          {/* User Profile */}
          <div className="relative ml-2">
            <button
              onClick={() => setIsUserMenuOpen(!isUserMenuOpen)}
              className="flex items-center gap-3 p-1.5 pr-4 rounded-full hover:bg-white/5 transition-all border border-transparent focus:outline-none focus:ring-2 focus:ring-kodo-cyan/50 group"
            >
              <div className="w-9 h-9 rounded-full bg-gradient-to-br from-kodo-cyan to-kodo-magenta p-[1.5px] shadow-lg shadow-kodo-cyan/10 group-hover:shadow-kodo-cyan/30 transition-shadow duration-300">
                <div className="w-full h-full rounded-full bg-kodo-ink flex items-center justify-center overflow-hidden">
                  {/* Placeholder Avatar */}
                  <span className="text-xs font-bold text-white group-hover:scale-110 transition-transform duration-300">
                    {user?.username?.substring(0, 2).toUpperCase() || 'VZ'}
                  </span>
                </div>
              </div>
              <div className="hidden lg:block text-left">
                <div className="text-xs font-bold text-white leading-none mb-1 group-hover:text-kodo-cyan transition-colors">
                  {user?.username}
                </div>
                <div className="text-[9px] text-kodo-text-dim uppercase tracking-wider font-mono">
                  LVL. 01
                </div>
              </div>
            </button>

            {isUserMenuOpen && (
              <FocusTrap active={isUserMenuOpen} onEscape={() => setIsUserMenuOpen(false)}>
                <div className="absolute right-0 top-full mt-2 w-64 bg-kodo-ink/90 backdrop-blur-xl border border-white/10 rounded-2xl shadow-2xl p-2 z-50 animate-scaleIn origin-top-right">
                  <div className="px-3 py-3 border-b border-white/5 mb-1">
                    <p className="text-sm font-bold text-white truncate text-center mb-1">{user?.username}</p>
                    <p className="text-xs text-kodo-text-dim truncate text-center font-mono">{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-kodo-text-dim hover:text-white hover:bg-white/5 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-kodo-text-dim hover:text-white hover:bg-white/5 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-kodo-red hover:bg-kodo-red/10 rounded-xl transition-colors">
                      <LogOut className="w-4 h-4" /> Déconnexion
                    </button>
                  </div>
                </div>
              </FocusTrap>
            )}
          </div>
        </div>
      </div>
    </header>
  );
}