'use client';

import React, { useState } from 'react';
import { Logo } from './ui/Logo';
import { Button } from './ui/Button';
import { Menu, X, User, Wind, Mic, User as UserIcon, Heart, ShoppingBag, Mail, Crown, MoreVertical, LogOut } from 'lucide-react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useAuth } from '../contexts/AuthContext';
import ForcePositionedModal from './auth/ForcePositionedModal';
import { SignupModal } from './auth/SignupModal';
import { UserProfile } from './auth/UserProfile';
import { FloatingHomeButton } from './ui/FloatingHomeButton';
import { AdminBadge } from './AdminIndicator';
import { UserRole } from '../types/auth';

const navigationItems = [
  { name: 'Oddech', href: '/', icon: Wind },
  { name: 'Podcast', href: '/podcast', icon: Mic },
  { name: 'O mnie', href: '/o-mnie', icon: UserIcon },
  { name: 'Dla Ciebie', href: '/dla-ciebie', icon: Heart },
  { name: 'Sklep', href: '/sklep', icon: ShoppingBag },
  { name: 'Kontakt', href: '/kontakt', icon: Mail },
];

export function Header() {
  const { user, logout } = useAuth();
  const pathname = usePathname();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [showLoginModal, setShowLoginModal] = useState(false);
  const [showSignupModal, setShowSignupModal] = useState(false);
  const [showUserProfile, setShowUserProfile] = useState(false);
  const [showUserMenu, setShowUserMenu] = useState(false);

  const handleAuthClick = () => {
    if (user) {
      setShowUserProfile(true);
    } else {
      setShowLoginModal(true);
    }
  };

  const handleLogout = async () => {
    try {
      await logout();
      setShowUserMenu(false);
    } catch (error) {
      console.error('Logout error:', error);
    }
  };

  // Close user menu when clicking outside
  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (showUserMenu && !target.closest('.user-menu-container')) {
        setShowUserMenu(false);
      }
    };

    if (showUserMenu) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => document.removeEventListener('mousedown', handleClickOutside);
    }
  }, [showUserMenu]);

  return (
    <>
      <header className="w-full bg-white/95 backdrop-blur-sm border-b border-orange-100 sticky top-0 z-30 shadow-sm">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            
            {/* Enhanced Logo with breathing animation */}
            <Logo />
            
            {/* Desktop Navigation - Better Responsive (1024px+) */}
            <nav className="hidden lg:flex items-center space-x-3 xl:space-x-4">
              {navigationItems.map((item) => (
                <Link
                  key={item.name}
                  href={item.href}
                  className={`px-2 xl:px-3 py-2 rounded-full text-sm font-medium transition-all duration-300 flex items-center space-x-1 xl:space-x-2 whitespace-nowrap ${
                    pathname === item.href
                      ? item.name === 'Oddech'
                        ? 'bg-gradient-to-r from-orange-400 to-yellow-400 text-white shadow-lg transform scale-105'
                        : 'bg-orange-100 text-orange-700'
                      : 'text-gray-600 hover:text-orange-600 hover:bg-orange-50'
                  }`}
                  title={item.name === 'Oddech' ? 'Wróć do centrum - weź oddech' : item.name}
                >
                  <item.icon className="w-4 h-4 flex-shrink-0" />
                  <span className="text-xs xl:text-sm">{item.name}</span>
                </Link>
              ))}
            </nav>

            {/* Medium Screen Navigation (768px - 1023px) - Icon Only */}
            <nav className="hidden md:flex lg:hidden items-center space-x-2">
              {navigationItems.map((item) => (
                <Link
                  key={item.name}
                  href={item.href}
                  className={`p-2 rounded-lg text-xs font-medium transition-all duration-300 flex items-center justify-center ${
                    pathname === item.href
                      ? item.name === 'Oddech'
                        ? 'bg-gradient-to-r from-orange-400 to-yellow-400 text-white shadow-lg'
                        : 'bg-orange-100 text-orange-700'
                      : 'text-gray-600 hover:text-orange-600 hover:bg-orange-50'
                  }`}
                  title={item.name}
                >
                  <item.icon className="w-4 h-4" />
                </Link>
              ))}
            </nav>
            
            {/* Auth Button & User Menu */}
            <div className="hidden md:flex gap-2 items-center">
              {/* Admin Panel Link for Super Admins */}
              {user?.role === UserRole.SUPER_ADMIN && (
                <Link
                  href="/admin"
                  className="flex items-center gap-2 px-3 py-2 bg-gradient-to-r from-purple-600 to-pink-600 text-white rounded-lg text-sm font-medium hover:from-purple-700 hover:to-pink-700 transition-all duration-300"
                >
                  <Crown size={16} />
                  <span className="hidden xl:inline">Admin Panel</span>
                  <span className="xl:hidden">Admin</span>
                </Link>
              )}
              
              {user ? (
                <div className="relative user-menu-container">
                  <button
                    onClick={() => setShowUserMenu(!showUserMenu)}
                    className="flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-300 hover:bg-orange-50 text-gray-700 hover:text-orange-600"
                    aria-label="Menu użytkownika"
                  >
                    <div className="w-8 h-8 rounded-full bg-gradient-to-br from-orange-400 to-yellow-400 flex items-center justify-center text-white font-semibold text-sm">
                      {user.name?.charAt(0).toUpperCase() || 'U'}
                    </div>
                    <MoreVertical size={18} className="text-gray-500" />
                  </button>

                  {/* User Menu Dropdown */}
                  {showUserMenu && (
                    <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-2 z-50 animate-fade-in">
                      <div className="px-4 py-2 border-b border-gray-100">
                        <p className="text-sm font-semibold text-gray-900">{user.name}</p>
                        <p className="text-xs text-gray-500 truncate">{user.email}</p>
                      </div>
                      
                      <button
                        onClick={() => {
                          setShowUserProfile(true);
                          setShowUserMenu(false);
                        }}
                        className="w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-orange-50 transition-colors flex items-center gap-2"
                      >
                        <User size={16} />
                        <span>Mój profil</span>
                      </button>

                      {user.role === UserRole.SUPER_ADMIN && (
                        <Link
                          href="/admin"
                          onClick={() => setShowUserMenu(false)}
                          className="block px-4 py-2 text-sm text-gray-700 hover:bg-orange-50 transition-colors flex items-center gap-2"
                        >
                          <Crown size={16} />
                          <span>Panel Admin</span>
                        </Link>
                      )}

                      <div className="border-t border-gray-100 mt-1 pt-1">
                        <button
                          onClick={handleLogout}
                          className="w-full px-4 py-2 text-left text-sm text-red-600 hover:bg-red-50 transition-colors flex items-center gap-2"
                        >
                          <LogOut size={16} />
                          <span>Wyloguj się</span>
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <Button 
                  variant="primary"
                  onClick={handleAuthClick}
                  className="flex items-center gap-2 text-sm"
                >
                  <span className="text-sm">Zaloguj się</span>
                </Button>
              )}
            </div>
            
            {/* Mobile Menu Button */}
            <button
              className="md:hidden p-2 rounded-lg hover:bg-gray-100 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
              aria-label={mobileOpen ? 'Zamknij menu' : 'Otwórz menu'}
              onClick={() => setMobileOpen(v => !v)}
            >
              {mobileOpen ? <X size={24} /> : <Menu size={24} />}
            </button>
          </div>
        </div>
        
        {/* Mobile Navigation */}
        {mobileOpen && (
          <div className="md:hidden bg-white/95 shadow-lg border-t border-gray-100">
            <nav className="px-4 py-3 space-y-1">
              {navigationItems.map((item) => (
                <Link
                  key={item.name}
                  href={item.href}
                  className={`block px-3 py-3 rounded-lg text-base font-medium transition-colors flex items-center space-x-3 ${
                    pathname === item.href
                      ? item.name === 'Oddech'
                        ? 'bg-gradient-to-r from-orange-400 to-yellow-400 text-white'
                        : 'bg-orange-100 text-orange-700'
                      : 'text-gray-600 hover:text-orange-600 hover:bg-orange-50'
                  }`}
                  onClick={() => setMobileOpen(false)}
                >
                  <item.icon className="w-5 h-5 flex-shrink-0" />
                  <span>{item.name}</span>
                </Link>
              ))}
              
              {/* Mobile auth button */}
              <div className="pt-2 border-t border-gray-100 mt-3 space-y-2">
                {/* Admin Panel Link for Super Admins (Mobile) */}
                {user?.role === UserRole.SUPER_ADMIN && (
                  <Link
                    href="/admin"
                    className="flex items-center gap-3 px-3 py-3 bg-gradient-to-r from-purple-600 to-pink-600 text-white rounded-lg font-medium hover:from-purple-700 hover:to-pink-700 transition-all duration-300"
                    onClick={() => setMobileOpen(false)}
                  >
                    <Crown size={20} />
                    <span>Admin Panel</span>
                  </Link>
                )}
                
                <Button 
                  variant={user ? "secondary" : "primary"}
                  onClick={() => {
                    handleAuthClick();
                    setMobileOpen(false);
                  }}
                  className="w-full justify-center gap-2"
                >
                  {user ? (
                    <>
                      <User size={16} />
                      <div className="flex items-center gap-2">
                        <span>{user.name}</span>
                        {user.role === UserRole.SUPER_ADMIN && (
                          <AdminBadge userRole={user.role} />
                        )}
                      </div>
                    </>
                  ) : (
                    'Zaloguj się'
                  )}
                </Button>
              </div>
            </nav>
          </div>
        )}
      </header>

      {/* Floating Home Button */}
      <FloatingHomeButton />

      {/* Auth Modals */}
      <ForcePositionedModal
        isOpen={showLoginModal}
        onClose={() => setShowLoginModal(false)}
        onSwitchToSignup={() => {
          setShowLoginModal(false);
          setShowSignupModal(true);
        }}
      />

      <SignupModal
        isOpen={showSignupModal}
        onClose={() => setShowSignupModal(false)}
        onSwitchToLogin={() => {
          setShowSignupModal(false);
          setShowLoginModal(true);
        }}
      />

      <UserProfile
        isOpen={showUserProfile}
        onClose={() => setShowUserProfile(false)}
      />
    </>
  );
} 