'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { UtensilsCrossed, Car, User, LogOut, Sparkles, LayoutGrid, Globe } from 'lucide-react';
import { getPlatformToken, clearPlatformSession } from '@/lib/auth';
import { authApi } from '@/lib/api';
import { AuthModal } from './AuthModal';

export default function Header() {
  const pathname = usePathname();
  const router = useRouter();
  const [token, setToken] = useState<string | null>(null);
  const [user, setUser] = useState<any>(null);
  const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);

  useEffect(() => {
    const currentToken = getPlatformToken();
    setToken(currentToken);

    if (currentToken) {
      authApi.getProfile()
        .then((res) => {
          if (res?.data) setUser(res.data);
        })
        .catch(() => { });
    }

    const handleMFEEvent = (e: any) => {
      if (e.detail?.type === 'MFE_AUTH_LOGIN') {
        setToken(e.detail.payload?.token);
        setUser(e.detail.payload?.user);
      } else if (e.detail?.type === 'MFE_LOGOUT' || e.detail?.type === 'MFE_AUTH_UNAUTHORIZED') {
        setToken(null);
        setUser(null);
      }
    };

    window.addEventListener('READY_MFE_EVENT', handleMFEEvent);
    return () => window.removeEventListener('READY_MFE_EVENT', handleMFEEvent);
  }, [pathname]);

  const handleLogout = async () => {
    await authApi.logout();
    clearPlatformSession();
    setToken(null);
    setUser(null);
    router.push('/');
  };

  const isFoodActive = pathname?.startsWith('/food');
  const isCabActive = pathname?.startsWith('/cab');

  return (
    <>
      <header className="sticky top-0 z-50 w-full border-b border-neutral-200 bg-white/95 backdrop-blur-md transition-all">
        <div className="mx-auto flex h-16 max-w-7xl items-center justify-between px-4 sm:px-6 lg:px-8">

          {/* Brand Logo matching ReadyCab style */}
          <div className="flex items-center gap-8">
            <Link href="/" className="flex items-center gap-3 group">
              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-black text-white shadow-sm transition-transform group-hover:scale-105">
                <Sparkles className="h-5 w-5" />
              </div>
              <div className="flex flex-col">
                <span className="text-lg font-bold tracking-tight text-neutral-900 flex items-center gap-1">
                  Ready<span className="text-black font-black">Go</span>
                </span>
                <span className="text-[11px] font-medium text-neutral-500 -mt-0.5">
                  Food &bull; Cab &bull; Services
                </span>
              </div>
            </Link>

            {/* Service Switcher Navigation Tabs */}
            <nav className="hidden md:flex items-center gap-1.5 rounded-full border border-neutral-200 bg-neutral-100 p-1">
              <Link
                href="/services"
                className={`flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs font-semibold transition-all ${pathname === '/services'
                  ? 'bg-white text-black shadow-sm'
                  : 'text-neutral-600 hover:text-black'
                  }`}
              >
                <LayoutGrid className="h-3.5 w-3.5" />
                All Services
              </Link>

              <a
                href="/food"
                className={`flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs font-semibold transition-all ${isFoodActive
                  ? 'bg-black text-white shadow-sm'
                  : 'text-neutral-600 hover:text-black'
                  }`}
              >
                <UtensilsCrossed className="h-3.5 w-3.5" />
                Food Delivery
              </a>

              <a
                href="/cab"
                className={`flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs font-semibold transition-all ${isCabActive
                  ? 'bg-black text-white shadow-sm'
                  : 'text-neutral-600 hover:text-black'
                  }`}
              >
                <Car className="h-3.5 w-3.5" />
                Cab Booking
              </a>
            </nav>
          </div>

          {/* Action Controls & Auth matching ReadyCab */}
          <div className="flex items-center gap-3">

            <a
              href="/cab/become-a-driver"
              className="hidden sm:inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs font-semibold text-white bg-black hover:bg-neutral-800 shadow-sm transition-all"
            >
              Become a Driver
            </a>

            <div className="flex items-center gap-1 text-xs text-neutral-600 px-2 py-1.5 rounded-full border border-neutral-200">
              <Globe className="h-3.5 w-3.5" />
              <span className="font-medium">EN</span>
            </div>

            {token ? (
              <div className="flex items-center gap-2">
                <Link
                  href="/profile"
                  className="flex items-center gap-2 rounded-full border border-neutral-200 bg-neutral-100 px-3.5 py-1.5 text-xs font-medium text-neutral-900 transition hover:bg-neutral-200"
                >
                  <div className="flex h-5 w-5 items-center justify-center rounded-full bg-black text-white text-[10px] font-bold">
                    {user?.name?.[0]?.toUpperCase() || 'U'}
                  </div>
                  <span className="hidden sm:inline-block max-w-[120px] truncate">
                    {user?.name || user?.first_name || 'My Account'}
                  </span>
                </Link>
                <button
                  onClick={handleLogout}
                  className="flex items-center justify-center h-8 w-8 rounded-full border border-neutral-200 bg-neutral-100 text-neutral-600 transition hover:bg-red-50 hover:text-red-600 hover:border-red-200"
                  title="Log out"
                >
                  <LogOut className="h-3.5 w-3.5" />
                </button>
              </div>
            ) : (
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={() => setIsAuthModalOpen(true)}
                  className="rounded-full border border-neutral-200 bg-white px-4 py-1.5 text-xs font-semibold text-neutral-900 transition hover:bg-neutral-100"
                >
                  Sign In
                </button>
                <button
                  type="button"
                  onClick={() => setIsAuthModalOpen(true)}
                  className="rounded-full bg-black px-4 py-1.5 text-xs font-semibold text-white shadow-sm transition hover:bg-neutral-800"
                >
                  Get Started
                </button>
              </div>
            )}
          </div>

        </div>
      </header>

      {/* Instant In-Page Auth Modal Popup */}
      <AuthModal
        isOpen={isAuthModalOpen}
        onClose={() => setIsAuthModalOpen(false)}
        onSuccess={() => {
          const currentToken = getPlatformToken();
          setToken(currentToken);
        }}
      />
    </>
  );
}
