'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { Menu, X, User, Settings, Home, MessageSquare, Users, CreditCard, Heart, MessageCircle, LogOut } from 'lucide-react';
import { usePathname } from 'next/navigation';
import { useAuth } from '@/contexts/auth-context';
import { BrandLogo } from '@/components/ui/brand-logo';
import { AddPropertyModal } from './add-property-modal';

type NavLabel = 'Home' | 'Buy' | 'Rent' | 'Off-Plan' | 'About' | 'Contact';

type BrandingData = {
  site_name: string;
  logo_url: string | null;
  tagline: string | null;
  logo_width?: number | null;
  logo_height?: number | null;
};

const NAV_LINKS: { label: NavLabel; href: string }[] = [
  { label: 'Home',     href: '/' },
  { label: 'Buy',      href: '/listings?listing_type=sale' },
  { label: 'Rent',     href: '/listings?listing_type=rent' },
  { label: 'Off-Plan', href: '/listings?completion_status=off_plan' },
  { label: 'About',    href: '/about' },
  { label: 'Contact',  href: '/contact' },
];

export function Navbar() {
  const pathname                            = usePathname();

  // Do not render the navbar on admin, dashboard, portal, pricing, support, or auth paths
  const isExcluded = pathname?.startsWith('/admin') ||
                     pathname?.startsWith('/dashboard') ||
                     pathname?.startsWith('/agency') ||
                     pathname?.startsWith('/agent') ||
                     pathname?.startsWith('/customer') ||
                     pathname?.startsWith('/developer') ||
                     pathname?.startsWith('/support') ||
                     pathname === '/login' ||
                     pathname === '/register' ||
                     pathname === '/forgot-password' ||
                     pathname === '/reset-password' ||
                     pathname === '/pricing';

  const [isScrolled, setIsScrolled]         = useState(false);
  const [activeTab, setActiveTab]           = useState<NavLabel>('Home');
  const [isMobileMenuOpen, setMobileMenu]   = useState(false);
  const [branding, setBranding]             = useState<BrandingData | null>(null);
  const { isAuthenticated, user, logout }   = useAuth();
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const isLightPage                         = pathname === '/about' || pathname === '/contact' || pathname?.startsWith('/listings');

  // Synchronize active navigation tab with actual pathname/search params on client
  useEffect(() => {
    if (isExcluded) return;
    if (pathname === '/') {
      setActiveTab('Home');
    } else if (pathname === '/about') {
      setActiveTab('About');
    } else if (pathname === '/contact') {
      setActiveTab('Contact');
    } else if (pathname?.startsWith('/listings')) {
      const searchParams = new URLSearchParams(window.location.search);
      const listingType = searchParams.get('listing_type');
      const completionStatus = searchParams.get('completion_status');
      if (listingType === 'sale') {
        setActiveTab('Buy');
      } else if (listingType === 'rent') {
        setActiveTab('Rent');
      } else if (completionStatus === 'off_plan') {
        setActiveTab('Off-Plan');
      }
    }
  }, [pathname, isExcluded]);

  // Close dropdown on click outside
  useEffect(() => {
    if (isExcluded || !isDropdownOpen) return;
    const close = () => setIsDropdownOpen(false);
    window.addEventListener('click', close);
    return () => window.removeEventListener('click', close);
  }, [isDropdownOpen, isExcluded]);

  useEffect(() => {
    if (isExcluded) return;
    fetch('/api/settings/branding')
      .then((res) => res.json())
      .then((data) => { if (data.success) setBranding(data.data); })
      .catch(() => {});
  }, [isExcluded]);

  useEffect(() => {
    if (isExcluded) return;
    const onScroll = () => setIsScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [isExcluded]);

  /* Close mobile menu on resize to desktop */
  useEffect(() => {
    if (isExcluded) return;
    const onResize = () => { if (window.innerWidth >= 768) setMobileMenu(false); };
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [isExcluded]);

  const handleLogout = async () => {
    setIsDropdownOpen(false);
    await logout();
    window.location.href = '/';
  };

  const scrolled = isScrolled;

  if (isExcluded) return null;

  return (
    <>
      {/* ── Top Bar ─────────────────────────────────────────── */}
      <header
        suppressHydrationWarning={true}
        className={`fixed top-0 left-0 w-full z-50 flex justify-between items-center
          px-6 sm:px-10 lg:px-20 h-[72px] md:h-20 transition-all duration-300
          ${scrolled
            ? 'bg-white/97 backdrop-blur-md shadow-[0_1px_24px_rgba(13,28,50,0.08)] border-b border-gray-100'
            : 'bg-transparent backdrop-blur-[6px] border-b border-white/10'
          }`}
      >
        {/* Logo */}
        <Link className="max-h-12 flex items-center select-none" href="/">
          <BrandLogo 
            theme={isLightPage || isScrolled ? 'light' : 'dark'} 
            className="transition-transform duration-300 hover:scale-[1.01]" 
          />
        </Link>

        {/* Desktop Nav */}
        <nav className="hidden md:flex items-center gap-8">
          {NAV_LINKS.map(({ label, href }) => (
            <Link
              key={label}
              href={href}
              onClick={() => setActiveTab(label)}
              className={`text-sm font-semibold transition-all duration-200 relative pb-0.5
                ${activeTab === label
                  ? `border-b-2 border-[#098E4B] ${scrolled ? 'text-[#111111]' : isLightPage ? 'text-[#111111]' : 'text-white'}`
                  : scrolled
                    ? 'text-[#666666] hover:text-[#111111]'
                    : isLightPage 
                      ? 'text-[#444444] hover:text-[#111111]' 
                      : 'text-white/75 hover:text-white'
              }`}
            >
              {label}
            </Link>
          ))}
        </nav>

        {/* Desktop CTA */}
        <div className="hidden md:flex items-center gap-3">
          {isAuthenticated && ['agent', 'agency', 'developer'].includes(user?.role || '') && (
            <button
              onClick={() => setIsAddModalOpen(true)}
              className="px-5 py-2 bg-[#098E4B] text-white text-xs font-bold uppercase
                tracking-widest hover:bg-[#077a3f] transition-all duration-200 active:scale-95 mr-2"
            >
              Place Your Ad
            </button>
          )}

          {isAuthenticated ? (
            <div className="relative">
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setIsDropdownOpen(!isDropdownOpen);
                }}
                className="flex items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-gray-100/5 transition-all focus:outline-none select-none"
              >
                {user?.avatar_url ? (
                  <img
                    src={user.avatar_url}
                    alt={user.first_name}
                    className="w-8 h-8 rounded-full object-cover border border-[#C5A880]/30 shadow-sm"
                  />
                ) : (
                  <div className="w-8 h-8 rounded-full bg-[#098E4B] border border-[#098E4B]/30 text-white flex items-center justify-center font-bold text-xs shadow-sm uppercase">
                    {user?.first_name ? user.first_name.charAt(0) : 'U'}
                  </div>
                )}
                <span className={`text-sm font-semibold select-none transition-colors duration-300 hidden sm:inline-block
                  ${scrolled ? 'text-[#111111]' : isLightPage ? 'text-[#111111]' : 'text-white'}`}>
                  {user?.first_name}
                </span>
                <span className={`text-[10px] select-none transition-colors duration-300
                  ${scrolled ? 'text-[#666666]' : isLightPage ? 'text-[#666666]' : 'text-white/60'}`}>
                  ▼
                </span>
              </button>

              {isDropdownOpen && (
                <div className="absolute right-0 mt-2.5 w-64 bg-white border border-[#E8E8E6] rounded-xl shadow-[0_10px_40px_rgba(9,142,75,0.12)] overflow-hidden z-50 animate-fade-in">
                  {/* User Profile Summary Header */}
                  <div className="px-5 py-4 border-b border-[#E8E8E6] bg-[#E8F5EE]">
                    <p className="text-xs font-bold text-[#111111] leading-none">{user?.first_name} {user?.last_name}</p>
                    <p className="text-[10px] text-[#666666] mt-1 truncate">{user?.email}</p>
                    <span className="inline-block mt-2 px-2 py-0.5 bg-[#098E4B]/10 text-[#098E4B] border border-[#098E4B]/20 text-[8px] font-bold uppercase tracking-wider rounded">
                      {user?.role?.replace('_', ' ')}
                    </span>
                  </div>

                  {/* Dropdown Options */}
                  <div className="py-1">
                    {/* --- Group 1: Account Basics --- */}
                    <div className="px-3 py-1.5 text-[9px] font-bold text-[#098E4B] uppercase tracking-widest bg-[#E8F5EE]/60 select-none">
                      Account Basics
                    </div>
                    <Link
                      href={user?.role === 'super_admin' ? '/admin' : `/${user?.role || 'customer'}?tab=overview`}
                      className="flex items-center gap-3 px-4 py-2.5 text-xs text-[#444444] hover:bg-[#E8F5EE] hover:text-[#098E4B] transition-colors"
                    >
                      <User className="w-3.5 h-3.5 shrink-0" />
                      My Profile
                    </Link>
                    <Link
                      href={user?.role === 'super_admin' ? '/admin/seo' : `/${user?.role || 'customer'}?tab=settings`}
                      className="flex items-center gap-3 px-4 py-2.5 text-xs text-[#444444] hover:bg-[#E8F5EE] hover:text-[#098E4B] transition-colors"
                    >
                      <Settings className="w-3.5 h-3.5 shrink-0" />
                      Account Settings
                    </Link>

                    {/* --- Group 2: Real Estate & Agency Options (Dynamic for Agent / Admin) --- */}
                    {['agent', 'agency', 'developer', 'super_admin'].includes(user?.role || '') && (
                      <>
                        <div className="border-t border-[#E8E8E6] my-1" />
                        <div className="px-3 py-1.5 text-[9px] font-bold text-[#098E4B] uppercase tracking-widest bg-[#E8F5EE]/60 select-none">
                          Real Estate Options
                        </div>
                        <Link
                          href={user?.role === 'super_admin' ? '/admin' : `/${user?.role}?tab=listings`}
                          className="flex items-center gap-3 px-4 py-2.5 text-xs text-[#444444] hover:bg-[#E8F5EE] hover:text-[#098E4B] transition-colors"
                        >
                          <Home className="w-3.5 h-3.5 shrink-0" />
                          My Properties / Listings
                        </Link>
                        <Link
                          href={user?.role === 'super_admin' ? '/admin' : `/${user?.role}?tab=bookings`}
                          className="flex items-center gap-3 px-4 py-2.5 text-xs text-[#444444] hover:bg-[#E8F5EE] hover:text-[#098E4B] transition-colors"
                        >
                          <MessageSquare className="w-3.5 h-3.5 shrink-0" />
                          Property Inquiries
                        </Link>
                        {user?.role !== 'super_admin' && (
                          <Link
                            href={`/${user?.role}?tab=overview`}
                            className="flex items-center gap-3 px-4 py-2.5 text-xs text-[#444444] hover:bg-[#E8F5EE] hover:text-[#098E4B] transition-colors"
                          >
                            <Users className="w-3.5 h-3.5 shrink-0" />
                            Lead Management
                          </Link>
                        )}
                        <Link
                          href={user?.role === 'super_admin' ? '/admin' : `/${user?.role}?tab=packages`}
                          className="flex items-center gap-3 px-4 py-2.5 text-xs text-[#444444] hover:bg-[#E8F5EE] hover:text-[#098E4B] transition-colors"
                        >
                          <CreditCard className="w-3.5 h-3.5 shrink-0" />
                          Subscription Plan / Invoices
                        </Link>
                      </>
                    )}

                    {/* --- Group 3: Interactions --- */}
                    <div className="border-t border-[#E8E8E6] my-1" />
                    <div className="px-3 py-1.5 text-[9px] font-bold text-[#098E4B] uppercase tracking-widest bg-[#E8F5EE]/60 select-none">
                      Interactions
                    </div>
                    <Link
                      href={user?.role === 'customer' ? '/customer' : `/${user?.role || 'customer'}?tab=overview`}
                      className="flex items-center gap-3 px-4 py-2.5 text-xs text-[#444444] hover:bg-[#E8F5EE] hover:text-[#098E4B] transition-colors"
                    >
                      <Heart className="w-3.5 h-3.5 shrink-0" />
                      My Favorites / Bookmarks
                    </Link>
                    <Link
                      href={user?.role === 'customer' ? '/customer' : `/${user?.role || 'customer'}?tab=overview`}
                      className="flex items-center gap-3 px-4 py-2.5 text-xs text-[#444444] hover:bg-[#E8F5EE] hover:text-[#098E4B] transition-colors"
                    >
                      <MessageCircle className="w-3.5 h-3.5 shrink-0" />
                      Chats / Messages
                    </Link>

                    {/* --- Group 4: Session Control --- */}
                    <div className="border-t border-[#E8E8E6] my-1" />
                    <button
                      onClick={handleLogout}
                      className="w-full flex items-center gap-3 px-4 py-3 text-xs text-[#C41B27] hover:bg-[#FDECEA] hover:text-[#a01520] transition-colors text-left font-bold"
                    >
                      <LogOut className="w-3.5 h-3.5 shrink-0" />
                      Sign Out
                    </button>
                  </div>
                </div>
              )}
            </div>
          ) : (
            <>
              <Link
                href="/register"
                className={`text-sm font-semibold transition-colors
                  ${scrolled ? 'text-[#666666] hover:text-[#111111]' : isLightPage ? 'text-[#555555] hover:text-[#111111]' : 'text-white/80 hover:text-white'}`}
              >
                Register
              </Link>
              <Link
                href="/login"
                className="px-6 py-2 bg-[#098E4B] text-white text-xs font-bold uppercase
                  tracking-widest hover:bg-[#077a3f] transition-colors duration-200 active:scale-95"
              >
                Sign In
              </Link>
            </>
          )}
        </div>

        {/* Mobile Toggle */}
        <button
          onClick={() => setMobileMenu(!isMobileMenuOpen)}
          className={`md:hidden p-2 rounded transition-colors
            ${scrolled ? 'text-[#111111]' : isLightPage ? 'text-[#111111]' : 'text-white'}`}
          aria-label="Toggle navigation"
        >
          {isMobileMenuOpen
            ? <X className="w-6 h-6" />
            : <Menu className="w-6 h-6" />}
        </button>
      </header>

      {/* ── Mobile Dropdown ─────────────────────────────────── */}
      {isMobileMenuOpen && (
        <div className="fixed top-[72px] left-0 w-full z-40 bg-white border-b border-[#E8E8E6]
          shadow-xl animate-slide-down md:hidden">
          <div className="flex flex-col px-6 py-6 gap-5">
            {NAV_LINKS.map(({ label, href }) => (
              <Link
                key={label}
                href={href}
                onClick={() => { setActiveTab(label); setMobileMenu(false); }}
                className={`text-sm font-semibold transition-colors
                  ${activeTab === label
                    ? 'text-[#098E4B]'
                    : 'text-[#555555] hover:text-[#111111]'}`}
              >
                {label}
              </Link>
            ))}

            {isAuthenticated && ['agent', 'agency', 'developer'].includes(user?.role || '') && (
              <button
                onClick={() => { setIsAddModalOpen(true); setMobileMenu(false); }}
                className="w-full py-3 bg-[#098E4B] text-white text-xs font-bold uppercase
                  tracking-widest hover:bg-[#077a3f] transition-colors text-center"
              >
                Place Your Ad
              </button>
            )}

            <hr className="border-[#E8E8E6]" />

            {isAuthenticated ? (
              <div className="flex flex-col gap-2.5">
                <div className="flex items-center gap-3 px-1 py-2">
                  {user?.avatar_url ? (
                    <img
                      src={user.avatar_url}
                      alt={user.first_name}
                      className="w-9 h-9 rounded-full object-cover border border-[#098E4B]/30"
                    />
                  ) : (
                    <div className="w-9 h-9 rounded-full bg-[#098E4B] text-white flex items-center justify-center font-bold text-xs uppercase border border-[#098E4B]/30">
                      {user?.first_name ? user.first_name.charAt(0) : 'U'}
                    </div>
                  )}
                  <div>
                    <p className="text-xs font-bold text-[#111111]">{user?.first_name} {user?.last_name}</p>
                    <p className="text-[10px] text-[#098E4B] uppercase font-semibold">{user?.role?.replace('_', ' ')}</p>
                  </div>
                </div>

                <hr className="border-[#E8E8E6]" />

                {/* Account Basics */}
                <Link
                  href={user?.role === 'super_admin' ? '/admin' : `/${user?.role || 'customer'}?tab=overview`}
                  onClick={() => setMobileMenu(false)}
                  className="flex items-center gap-3 px-1 py-1.5 text-xs text-[#555555] hover:text-[#098E4B]"
                >
                  <User className="w-4 h-4 text-[#098E4B]" />
                  My Profile
                </Link>
                <Link
                  href={user?.role === 'super_admin' ? '/admin/seo' : `/${user?.role || 'customer'}?tab=settings`}
                  onClick={() => setMobileMenu(false)}
                  className="flex items-center gap-3 px-1 py-1.5 text-xs text-[#555555] hover:text-[#098E4B]"
                >
                  <Settings className="w-4 h-4 text-[#098E4B]" />
                  Account Settings
                </Link>

                {/* Real Estate & Agency Options (Dynamic) */}
                {['agent', 'agency', 'developer', 'super_admin'].includes(user?.role || '') && (
                  <>
                    <Link
                      href={user?.role === 'super_admin' ? '/admin' : `/${user?.role}?tab=listings`}
                      onClick={() => setMobileMenu(false)}
                      className="flex items-center gap-3 px-1 py-1.5 text-xs text-[#555555] hover:text-[#098E4B]"
                    >
                      <Home className="w-4 h-4 text-[#098E4B]" />
                      My Properties / Listings
                    </Link>
                    <Link
                      href={user?.role === 'super_admin' ? '/admin' : `/${user?.role}?tab=bookings`}
                      onClick={() => setMobileMenu(false)}
                      className="flex items-center gap-3 px-1 py-1.5 text-xs text-[#555555] hover:text-[#098E4B]"
                    >
                      <MessageSquare className="w-4 h-4 text-[#098E4B]" />
                      Property Inquiries
                    </Link>
                    <Link
                      href={user?.role === 'super_admin' ? '/admin' : `/${user?.role}?tab=packages`}
                      onClick={() => setMobileMenu(false)}
                      className="flex items-center gap-3 px-1 py-1.5 text-xs text-[#555555] hover:text-[#098E4B]"
                    >
                      <CreditCard className="w-4 h-4 text-[#098E4B]" />
                      Subscription Plan / Invoices
                    </Link>
                  </>
                )}

                {/* Interactions */}
                <Link
                  href={user?.role === 'customer' ? '/customer' : `/${user?.role || 'customer'}?tab=overview`}
                  onClick={() => setMobileMenu(false)}
                  className="flex items-center gap-3 px-1 py-1.5 text-xs text-[#555555] hover:text-[#098E4B]"
                >
                  <Heart className="w-4 h-4 text-[#098E4B]" />
                  My Favorites / Bookmarks
                </Link>

                <hr className="border-[#E8E8E6] mt-2" />

                <button
                  onClick={() => { logout(); setMobileMenu(false); window.location.href = '/'; }}
                  className="w-full py-3 bg-[#C41B27] hover:bg-[#a01520] text-white text-xs font-bold uppercase
                    tracking-widest transition-colors text-center mt-2"
                >
                  Sign Out
                </button>
              </div>
            ) : (
              <div className="flex flex-col gap-3">
                <Link
                  href="/register"
                  onClick={() => setMobileMenu(false)}
                  className="w-full py-3 border border-[#098E4B] text-[#098E4B] text-xs
                    font-bold uppercase tracking-widest hover:bg-[#098E4B] hover:text-white
                    transition-colors text-center"
                >
                  Register
                </Link>
                <Link
                  href="/login"
                  onClick={() => setMobileMenu(false)}
                  className="w-full py-3 bg-[#098E4B] text-white text-xs font-bold uppercase
                    tracking-widest hover:bg-[#077a3f] transition-colors text-center"
                >
                  Sign In
                </Link>
              </div>
            )}
          </div>
        </div>
      )}

      {isAddModalOpen && (
        <AddPropertyModal
          open={isAddModalOpen}
          onClose={() => setIsAddModalOpen(false)}
          onSuccess={(id, slug) => {
            setIsAddModalOpen(false);
            window.location.href = '/listings';
          }}
        />
      )}
    </>
  );
}
