import React, { useState, useRef } from 'react';
import { Link } from 'react-router-dom';
import { 
  Hotel, 
  User, 
  LogOut, 
  LogIn, 
  UserPlus,
  Heart,
  Phone,
  Mail,
  Calendar,
  Star,
  Users,
  AlertCircle,
} from 'lucide-react';
import { useClickOutside } from '../hooks/useClickOutside';
import { useCompanySettings } from '../contexts/CompanySettingsContext';
import { useAuthModal } from '../../features/auth/contexts/AuthModalContext';
import { normalizeImageUrl } from '../utils/imageUtils';
import InAppNotificationBell from '../../features/notifications/components/InAppNotificationBell';
import Navbar from './Navbar';

interface HeaderProps {
  isAuthenticated?: boolean;
  userInfo?: {
    name: string;
    email: string;
    avatar?: string;
    role: string;
  } | null;
  onLogout?: () => void;
}

const Header: React.FC<HeaderProps> = ({ 
  isAuthenticated = false, 
  userInfo = null,
  onLogout 
}) => {
  const { settings } = useCompanySettings();
  const { openModal } = useAuthModal();

  
  const displayPhone = settings.company_phone || '+1 (234) 567-890';
  const displayEmail = settings.company_email || 'info@luxuryhotel.com';
  const logoUrl = settings.company_logo_url
    ? (settings.company_logo_url.startsWith('http')
        ? settings.company_logo_url
        : `${import.meta.env.VITE_API_URL || 'http://localhost:8000'}${settings.company_logo_url}`)
    : null;
  const [isMobileMenuOpen, setIsMobileMenuOpen] = 
    useState(false);
  const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
  const userMenuRef = useRef<HTMLDivElement>(null);

  
  useClickOutside(userMenuRef, () => {
    if (isUserMenuOpen) {
      setIsUserMenuOpen(false);
    }
  });

  const toggleMobileMenu = () => {
    setIsMobileMenuOpen(!isMobileMenuOpen);
  };

  const toggleUserMenu = () => {
    setIsUserMenuOpen(!isUserMenuOpen);
  };

  const handleLogout = () => {
    if (onLogout) {
      onLogout();
    }
    setIsUserMenuOpen(false);
    setIsMobileMenuOpen(false);
  };

  // Mobile menu content with user authentication
  const mobileMenuContent = (
    <>
      {!isAuthenticated ? (
        <>
          <button
            onClick={() => {
              setIsMobileMenuOpen(false);
              openModal('login');
            }}
            className="flex items-center 
              space-x-2 px-4 py-3 text-white/90 
              hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
              rounded-sm transition-all duration-300 
              border-l-2 border-transparent 
              hover:border-[#d4af37] font-light tracking-wide w-full text-left"
          >
            <LogIn className="w-4 h-4" />
            <span>Login</span>
          </button>
          <button
            onClick={() => {
              setIsMobileMenuOpen(false);
              openModal('register');
            }}
            className="flex items-center 
              space-x-2 px-4 py-3 bg-gradient-to-r 
              from-[#d4af37] to-[#c9a227] text-[#0f0f0f] 
              rounded-sm hover:from-[#f5d76e] 
              hover:to-[#d4af37] transition-all 
              duration-300 font-medium tracking-wide 
              mt-2 w-full text-left"
          >
            <UserPlus className="w-4 h-4" />
            <span>Register</span>
          </button>
        </>
      ) : (
        <>
          <div className="px-4 py-2 text-sm 
            text-[#d4af37]/70 font-light tracking-wide"
          >
            Hello, {userInfo?.name}
          </div>
          <Link
            to="/profile"
            onClick={() => 
              setIsMobileMenuOpen(false)
            }
            className="flex items-center 
              space-x-2 px-4 py-3 text-white/90 
              hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
              rounded-sm transition-all duration-300 
              border-l-2 border-transparent 
              hover:border-[#d4af37] font-light tracking-wide"
          >
            <User className="w-4 h-4" />
            <span>Profile</span>
          </Link>
          {userInfo?.role !== 'admin' && userInfo?.role !== 'staff' && userInfo?.role !== 'accountant' && userInfo?.role !== 'housekeeping' && (
            <>
              <Link
                to="/favorites"
                onClick={() => 
                  setIsMobileMenuOpen(false)
                }
                className="flex items-center 
                  space-x-2 px-4 py-3 text-white/90 
                  hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                  rounded-sm transition-all duration-300 
                  border-l-2 border-transparent 
                  hover:border-[#d4af37] font-light tracking-wide"
              >
                <Heart className="w-4 h-4" />
                <span>Favorites</span>
              </Link>
              <Link
                to="/bookings"
                onClick={() => 
                  setIsMobileMenuOpen(false)
                }
                className="flex items-center 
                  space-x-2 px-4 py-3 text-white/90 
                  hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                  rounded-sm transition-all duration-300 
                  border-l-2 border-transparent 
                  hover:border-[#d4af37] font-light tracking-wide"
              >
                <Calendar className="w-4 h-4" />
                <span>My Bookings</span>
              </Link>
              <Link
                to="/loyalty"
                onClick={() => 
                  setIsMobileMenuOpen(false)
                }
                className="flex items-center 
                  space-x-2 px-4 py-3 text-white/90 
                  hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                  rounded-sm transition-all duration-300 
                  border-l-2 border-transparent 
                  hover:border-[#d4af37] font-light tracking-wide"
              >
                <Star className="w-4 h-4" />
                <span>Loyalty Program</span>
              </Link>
              <Link
                to="/group-bookings"
                onClick={() => 
                  setIsMobileMenuOpen(false)
                }
                className="flex items-center 
                  space-x-2 px-4 py-3 text-white/90 
                  hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                  rounded-sm transition-all duration-300 
                  border-l-2 border-transparent 
                  hover:border-[#d4af37] font-light tracking-wide"
              >
                <Users className="w-4 h-4" />
                <span>Group Bookings</span>
              </Link>
              <Link
                to="/complaints"
                onClick={() => 
                  setIsMobileMenuOpen(false)
                }
                className="flex items-center 
                  space-x-2 px-4 py-3 text-white/90 
                  hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                  rounded-sm transition-all duration-300 
                  border-l-2 border-transparent 
                  hover:border-[#d4af37] font-light tracking-wide"
              >
                <AlertCircle className="w-4 h-4" />
                <span>Complaints</span>
              </Link>
            </>
          )}
          {userInfo?.role === 'admin' && (
            <Link
              to="/admin"
              onClick={() => 
                setIsMobileMenuOpen(false)
              }
              className="flex items-center 
                space-x-2 px-4 py-3 text-white/90 
                hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                rounded-sm transition-all duration-300 
                border-l-2 border-transparent 
                hover:border-[#d4af37] font-light tracking-wide"
            >
              <User className="w-4 h-4" />
              <span>Admin</span>
            </Link>
          )}
          {userInfo?.role === 'staff' && (
            <Link
              to="/staff"
              onClick={() => 
                setIsMobileMenuOpen(false)
              }
              className="flex items-center 
                space-x-2 px-4 py-3 text-white/90 
                hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                rounded-sm transition-all duration-300 
                border-l-2 border-transparent 
                hover:border-[#d4af37] font-light tracking-wide"
            >
              <User className="w-4 h-4" />
              <span>Staff Dashboard</span>
            </Link>
          )}
          {userInfo?.role === 'accountant' && (
            <Link
              to="/accountant"
              onClick={() => 
                setIsMobileMenuOpen(false)
              }
              className="flex items-center 
                space-x-2 px-4 py-3 text-white/90 
                hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                rounded-sm transition-all duration-300 
                border-l-2 border-transparent 
                hover:border-[#d4af37] font-light tracking-wide"
            >
              <User className="w-4 h-4" />
              <span>Accountant Dashboard</span>
            </Link>
          )}
          <div className="border-t border-[#d4af37]/20 my-2"></div>
          <button
            onClick={handleLogout}
            className="w-full flex items-center 
              space-x-2 px-4 py-3 text-red-400/90 
              hover:bg-red-500/10 hover:text-red-400 
              rounded-sm transition-all duration-300 
              border-l-2 border-transparent 
              hover:border-red-500/50 text-left 
              font-light tracking-wide"
          >
            <LogOut className="w-4 h-4" />
            <span>Logout</span>
          </button>
        </>
      )}
    </>
  );

  return (
    <header className="bg-gradient-to-b from-[#1a1a1a] to-[#0f0f0f] sticky top-0 z-50 border-b border-[#d4af37]/20 shadow-2xl">
      <div className="hidden lg:block bg-[#0a0a0a]/50 border-b border-[#d4af37]/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-2">
          <div className="flex items-center justify-end space-x-6 text-sm">
            {displayPhone && (
              <a href={`tel:${displayPhone.replace(/\s+/g, '').replace(/[()]/g, '')}`} className="flex items-center space-x-2 text-[#d4af37] hover:text-[#f5d76e] transition-colors duration-300 font-light">
                <Phone className="w-3.5 h-3.5" />
                <span className="tracking-wide">{displayPhone}</span>
              </a>
            )}
            {displayEmail && (
              <a href={`mailto:${displayEmail}`} className="flex items-center space-x-2 text-[#d4af37] hover:text-[#f5d76e] transition-colors duration-300 font-light">
                <Mail className="w-3.5 h-3.5" />
                <span className="tracking-wide">{displayEmail}</span>
              </a>
            )}
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <div className="flex items-center justify-between">
          <Link 
            to="/" 
            className="flex items-center space-x-3 
              group transition-all duration-300 hover:opacity-90"
          >
            {logoUrl ? (
              <div className="relative">
                <img 
                  src={logoUrl}
                  alt={settings.company_name}
                  className="h-10 w-auto object-contain drop-shadow-lg"
                />
              </div>
            ) : (
              <div className="relative">
                <div className="absolute inset-0 bg-gradient-to-br from-[#d4af37] to-[#f5d76e] rounded-full blur-md opacity-30 group-hover:opacity-50 transition-opacity duration-300"></div>
                <Hotel className="relative w-10 h-10 text-[#d4af37] drop-shadow-lg" />
              </div>
            )}
            <div className="flex flex-col">
              <span className="text-2xl font-display font-semibold text-white tracking-tight leading-tight">
                {settings.company_name}
              </span>
              <span className="text-[10px] text-[#d4af37] tracking-[0.2em] uppercase font-light">
                {settings.company_tagline || 'Excellence Redefined'}
              </span>
            </div>
          </Link>

          <Navbar 
            isMobileMenuOpen={isMobileMenuOpen}
            onMobileMenuToggle={toggleMobileMenu}
            onLinkClick={() => setIsMobileMenuOpen(false)}
            mobileMenuContent={mobileMenuContent}
          />

          <div className="hidden md:flex items-center 
            space-x-3"
          >
            {!isAuthenticated ? (
              <>
                <button
                  onClick={() => openModal('login')}
                  className="flex items-center space-x-2 
                    px-5 py-2 text-white/90 
                    hover:text-[#d4af37] transition-all duration-300 
                    font-light tracking-wide relative group"
                >
                  <LogIn className="w-4 h-4 relative z-10" />
                  <span className="relative z-10">Login</span>
                  <span className="absolute inset-0 border border-[#d4af37]/30 rounded-sm opacity-0 group-hover:opacity-100 transition-opacity duration-300"></span>
                </button>
                <button
                  onClick={() => openModal('register')}
                  className="flex items-center space-x-2 
                    px-6 py-2.5 bg-gradient-to-r from-[#d4af37] to-[#c9a227] 
                    text-[#0f0f0f] rounded-sm hover:from-[#f5d76e] 
                    hover:to-[#d4af37] transition-all duration-300 
                    font-medium tracking-wide shadow-lg shadow-[#d4af37]/20 
                    hover:shadow-[#d4af37]/30 relative overflow-hidden group"
                >
                  <span className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700"></span>
                  <UserPlus className="w-4 h-4 relative z-10" />
                  <span className="relative z-10">Register</span>
                </button>
              </>
            ) : (
              <div className="flex items-center gap-3">
                {isAuthenticated && <InAppNotificationBell />}
                <div className="relative" ref={userMenuRef}>
                  <button
                    onClick={toggleUserMenu}
                    className="flex items-center space-x-3 
                      px-3 py-2 rounded-sm hover:bg-white/10 
                      transition-all duration-300 border border-transparent 
                      hover:border-[#d4af37]/30"
                  >
                    {userInfo?.avatar ? (
                      <img 
                        src={normalizeImageUrl(userInfo.avatar)} 
                        alt={userInfo.name}
                        className="w-9 h-9 rounded-full 
                          object-cover ring-2 ring-[#d4af37]/50"
                      />
                    ) : (
                      <div className="w-9 h-9 bg-gradient-to-br from-[#d4af37] to-[#c9a227] 
                        rounded-full flex items-center 
                        justify-center ring-2 ring-[#d4af37]/50 shadow-lg"
                      >
                        <span className="text-[#0f0f0f] 
                          font-semibold text-sm"
                        >
                          {userInfo?.name?.charAt(0)
                            .toUpperCase()}
                        </span>
                      </div>
                    )}
                    <span className="font-light text-white/90 tracking-wide">
                      {userInfo?.name}
                    </span>
                  </button>

                  {isUserMenuOpen && (
                  <div className="absolute right-0 mt-2 
                    w-52 bg-gradient-to-b from-[#1a1a1a] to-[#0f0f0f] 
                    rounded-sm shadow-2xl py-2 border border-[#d4af37]/20 
                    z-50 backdrop-blur-xl animate-fade-in"
                  >
                    <Link
                      to="/profile"
                      onClick={() => setIsUserMenuOpen(false)}
                      className="flex items-center space-x-3 
                        px-4 py-2.5 text-white/90 
                        hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                        transition-all duration-300 border-l-2 border-transparent 
                        hover:border-[#d4af37]"
                    >
                      <User className="w-4 h-4" />
                      <span className="font-light tracking-wide">Profile</span>
                    </Link>
                    {userInfo?.role !== 'admin' && userInfo?.role !== 'staff' && userInfo?.role !== 'accountant' && userInfo?.role !== 'housekeeping' && (
                      <>
                        <Link
                          to="/favorites"
                          onClick={() => setIsUserMenuOpen(false)}
                          className="flex items-center space-x-3 
                            px-4 py-2.5 text-white/90 
                            hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                            transition-all duration-300 border-l-2 border-transparent 
                            hover:border-[#d4af37]"
                        >
                          <Heart className="w-4 h-4" />
                          <span className="font-light tracking-wide">Favorites</span>
                        </Link>
                        <Link
                          to="/bookings"
                          onClick={() => setIsUserMenuOpen(false)}
                          className="flex items-center space-x-3 
                            px-4 py-2.5 text-white/90 
                            hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                            transition-all duration-300 border-l-2 border-transparent 
                            hover:border-[#d4af37]"
                        >
                          <Calendar className="w-4 h-4" />
                          <span className="font-light tracking-wide">My Bookings</span>
                        </Link>
                        <Link
                          to="/loyalty"
                          onClick={() => setIsUserMenuOpen(false)}
                          className="flex items-center space-x-3 
                            px-4 py-2.5 text-white/90 
                            hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                            transition-all duration-300 border-l-2 border-transparent 
                            hover:border-[#d4af37]"
                        >
                          <Star className="w-4 h-4" />
                          <span className="font-light tracking-wide">Loyalty Program</span>
                        </Link>
                        <Link
                          to="/group-bookings"
                          onClick={() => setIsUserMenuOpen(false)}
                          className="flex items-center space-x-3 
                            px-4 py-2.5 text-white/90 
                            hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                            transition-all duration-300 border-l-2 border-transparent 
                            hover:border-[#d4af37]"
                        >
                          <Users className="w-4 h-4" />
                          <span className="font-light tracking-wide">Group Bookings</span>
                        </Link>
                        <Link
                          to="/complaints"
                          onClick={() => setIsUserMenuOpen(false)}
                          className="flex items-center space-x-3 
                            px-4 py-2.5 text-white/90 
                            hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                            transition-all duration-300 border-l-2 border-transparent 
                            hover:border-[#d4af37]"
                        >
                          <AlertCircle className="w-4 h-4" />
                          <span className="font-light tracking-wide">Complaints</span>
                        </Link>
                      </>
                    )}
                    {userInfo?.role === 'admin' && (
                      <Link
                        to="/admin"
                        onClick={() => 
                          setIsUserMenuOpen(false)
                        }
                        className="flex items-center 
                          space-x-3 px-4 py-2.5 text-white/90 
                          hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                          transition-all duration-300 border-l-2 border-transparent 
                          hover:border-[#d4af37]"
                      >
                        <User className="w-4 h-4" />
                        <span className="font-light tracking-wide">Admin</span>
                      </Link>
                    )}
                    {userInfo?.role === 'staff' && (
                      <Link
                        to="/staff"
                        onClick={() => 
                          setIsUserMenuOpen(false)
                        }
                        className="flex items-center 
                          space-x-3 px-4 py-2.5 text-white/90 
                          hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                          transition-all duration-300 border-l-2 border-transparent 
                          hover:border-[#d4af37]"
                      >
                        <User className="w-4 h-4" />
                        <span className="font-light tracking-wide">Staff Dashboard</span>
                      </Link>
                    )}
                    {userInfo?.role === 'accountant' && (
                      <Link
                        to="/accountant"
                        onClick={() => 
                          setIsUserMenuOpen(false)
                        }
                        className="flex items-center 
                          space-x-3 px-4 py-2.5 text-white/90 
                          hover:bg-[#d4af37]/10 hover:text-[#d4af37] 
                          transition-all duration-300 border-l-2 border-transparent 
                          hover:border-[#d4af37]"
                      >
                        <User className="w-4 h-4" />
                        <span className="font-light tracking-wide">Accountant Dashboard</span>
                      </Link>
                    )}
                    <div className="border-t border-[#d4af37]/20 my-1"></div>
                    <button
                      onClick={handleLogout}
                      className="w-full flex items-center 
                        space-x-3 px-4 py-2.5 text-red-400/90 
                        hover:bg-red-500/10 hover:text-red-400 
                        transition-all duration-300 border-l-2 border-transparent 
                        hover:border-red-500/50 text-left"
                    >
                      <LogOut className="w-4 h-4" />
                      <span className="font-light tracking-wide">Logout</span>
                    </button>
                  </div>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </header>
  );
};

export default Header;
