'use client';

import React from 'react';
import { usePathname } from 'next/navigation';
import Link from 'next/link';
import {
  ShoppingCart,
  Menu,
  X,
  ChevronDown,
  LayoutDashboard,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '@/lib/utils';
import { useCart } from '@/hooks/useCart';
import { useIsAdmin, useUser } from '@/store/auth.store';
import Image from 'next/image';
import { useLogout } from '@/hooks';

type NavItem = {
  label: string;
  href?: string;
  children?: { label: string; href: string }[];
};

const NAV_ITEMS: NavItem[] = [
  { label: 'BERANDA', href: '/' },
  { label: 'TOKO', href: '/products' },
  {
    label: 'INSPIRASI',
    children: [
      { label: 'RESEP', href: '/recipes' },
      { label: 'AKTIVITAS', href: '/activities' },
      { label: 'ARTIKEL', href: '/articles' },
    ],
  },
  {
    label: 'INFORMASI',
    children: [
      { label: 'EVENT & PROMO', href: '/event-promo' },
      { label: 'CSR', href: '/csr' },
      { label: 'CARI AGEN', href: '/agen' },
    ],
  },
];

function isPathActive(pathname: string, href: string) {
  if (href === '/') return pathname === '/';
  return pathname === href || pathname.startsWith(`${href}/`);
}

export default function Navbar() {
  const pathname = usePathname();
  const [isMenuOpen, setIsMenuOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  const [isMounted, setIsMounted] = React.useState(false);
  const [userMenuOpen, setUserMenuOpen] = React.useState(false);

  const user = useUser();
  const isAdmin = useIsAdmin();
  const { data: cart } = useCart();
  const logout = useLogout();

  const items = cart?.items ?? [];
  const cartCount = cart?.item_count ?? items.length;

  React.useEffect(() => {
    setIsMounted(true);
    const handleScroll = () => setScrolled(window.scrollY > 50);
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  React.useEffect(() => {
    setIsMenuOpen(false);
    setUserMenuOpen(false);
  }, [pathname]);

  const dashboardHref =
    user?.user_type === 'admin' ? '/dashboard/admin' : '/dashboard/user/cart';

  return (
    <>
      <header
        className={cn(
          'fixed top-0 left-0 right-0 z-50 transition-all duration-500',
          scrolled
            ? 'bg-white/95 backdrop-blur-xl border-b border-[#E8E0CC]/80 shadow-sm shadow-[#FFD738]/5 py-2'
            : 'bg-white/30 backdrop-blur-md border-b border-white/20 py-4'
        )}
      >
        <div className="container mx-auto px-4 flex items-center justify-between">
          {/* Logo */}
          <Link
            href="/"
            className="flex items-center gap-3 cursor-pointer group"
          >
            <div className="relative">
              <div className="absolute inset-0 bg-[#FFD738]/30 rounded-full blur-md group-hover:blur-lg transition-all" />
              <Image
                src={'/logo.avif'}
                width={40}
                height={40}
                alt="Garam Cap Kapal Logo"
                className="relative z-10"
              />
            </div>
            <div className="hidden sm:block">
              <p className="font-black text-[#1C1D1F] text-sm uppercase tracking-wider leading-none">
                Garam <span className="text-[#D4A000]">Cap Kapal</span>
              </p>
              <p className="text-[9px] font-bold text-[#9CA3AF] uppercase tracking-widest mt-0.5">
                Sejak 1978
              </p>
            </div>
          </Link>

          {/* Desktop Nav */}
          <nav className="hidden lg:flex items-center gap-1">
            {NAV_ITEMS.map((item) => {
              const isActive = item.href
                ? isPathActive(pathname, item.href)
                : false;
              const isChildActive = item.children?.some((child) =>
                isPathActive(pathname, child.href)
              );
              const active = isActive || isChildActive;

              return (
                <div key={item.label} className="relative group">
                  {item.href ? (
                    <Link
                      href={item.href}
                      className={cn(
                        'px-4 py-2 rounded-xl text-xs font-bold uppercase tracking-widest transition-all duration-200 block relative',
                        active
                          ? 'text-[#D4A000] bg-[#FFD738]/10'
                          : 'text-[#6B7280] hover:text-[#1C1D1F] hover:bg-black/5'
                      )}
                    >
                      {item.label}
                      {active && (
                        <motion.span
                          layoutId="nav-indicator"
                          className="absolute bottom-1 left-1/2 -translate-x-1/2 w-4 h-0.5 bg-[#FFD738] rounded-full"
                        />
                      )}
                    </Link>
                  ) : (
                    <button
                      className={cn(
                        'px-4 py-2 rounded-xl text-xs font-bold uppercase tracking-widest transition-all duration-200 flex items-center gap-1 relative',
                        active
                          ? 'text-[#D4A000] bg-[#FFD738]/10'
                          : 'text-[#6B7280] group-hover:text-[#1C1D1F] group-hover:bg-black/5'
                      )}
                    >
                      {item.label}
                      <ChevronDown
                        size={14}
                        className={cn(
                          'transition-transform duration-300 group-hover:rotate-180',
                          active ? 'text-[#D4A000]' : 'text-[#9CA3AF]'
                        )}
                      />
                      {active && (
                        <motion.span
                          layoutId="nav-indicator"
                          className="absolute bottom-1 left-1/2 -translate-x-1/2 w-4 h-0.5 bg-[#FFD738] rounded-full"
                        />
                      )}
                    </button>
                  )}

                  {item.children && (
                    <div className="absolute top-full left-1/2 -translate-x-1/2 pt-2 opacity-0 translate-y-2 pointer-events-none group-hover:opacity-100 group-hover:translate-y-0 group-hover:pointer-events-auto transition-all duration-200 w-48 z-50">
                      <div className="bg-white/95 backdrop-blur-xl border border-[#E8E0CC]/80 rounded-2xl shadow-xl shadow-black/5 p-1.5 flex flex-col gap-1">
                        {item.children.map((child) => {
                          const childActive = isPathActive(
                            pathname,
                            child.href
                          );
                          return (
                            <Link
                              key={child.href}
                              href={child.href}
                              className={cn(
                                'px-3 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider transition-colors block',
                                childActive
                                  ? 'bg-[#FFD738]/15 text-[#D4A000]'
                                  : 'text-[#6B7280] hover:text-[#1C1D1F] hover:bg-[#FFF9E8]'
                              )}
                            >
                              {child.label}
                            </Link>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </nav>

          {/* Actions */}
          <div className="flex items-center gap-2">
            {/* Cart */}
            {!isAdmin && (
              <Link
                href="/dashboard/user/cart"
                className="relative p-2.5 rounded-xl bg-white/60 backdrop-blur-sm border border-[#E8E0CC]/80 text-[#6B7280] hover:text-[#1C1D1F] hover:border-[#FFD738]/50 hover:bg-[#FFF9E8] transition-all duration-200 shadow-sm"
              >
                <ShoppingCart size={18} />
                {user && cartCount > 0 && (
                  <span className="absolute -top-1 -right-1 w-4 h-4 bg-[#FFD738] text-[#1C1D1F] text-[9px] font-black flex items-center justify-center rounded-full ring-2 ring-white">
                    {cartCount}
                  </span>
                )}
              </Link>
            )}

            {/* User / Auth */}
            {!isMounted ? (
              <div className="w-28 h-9 bg-[#E8E0CC]/50 animate-pulse rounded-xl" />
            ) : user ? (
              <div className="relative">
                <button
                  onClick={() => setUserMenuOpen(!userMenuOpen)}
                  className="flex items-center gap-2 px-3 py-2 rounded-xl bg-white/60 backdrop-blur-sm border border-[#E8E0CC]/80 hover:border-[#FFD738]/50 hover:bg-[#FFF9E8] transition-all duration-200 shadow-sm"
                >
                  <div className="w-7 h-7 bg-linear-to-br from-[#FFD738] to-[#D4A000] rounded-full flex items-center justify-center text-[#1C1D1F] font-black text-xs">
                    {user.name[0]}
                  </div>
                  <span className="hidden md:block text-xs font-bold text-[#1C1D1F] max-w-[80px] truncate">
                    {user.name.split(' ')[0]}
                  </span>
                  <ChevronDown
                    size={12}
                    className={cn(
                      'text-[#9CA3AF] transition-transform',
                      userMenuOpen && 'rotate-180'
                    )}
                  />
                </button>

                <AnimatePresence>
                  {userMenuOpen && (
                    <motion.div
                      initial={{ opacity: 0, y: 8, scale: 0.95 }}
                      animate={{ opacity: 1, y: 0, scale: 1 }}
                      exit={{ opacity: 0, y: 8, scale: 0.95 }}
                      transition={{ duration: 0.15 }}
                      className="absolute right-0 top-full mt-2 w-48 bg-white/80 backdrop-blur-xl border border-[#E8E0CC]/80 rounded-2xl shadow-xl shadow-black/5 p-1.5 overflow-hidden"
                    >
                      <Link
                        href={dashboardHref}
                        className="flex items-center gap-2 w-full px-3 py-2.5 text-xs font-bold text-[#1C1D1F] hover:bg-[#FFF9E8] rounded-xl transition-colors uppercase tracking-wider"
                      >
                        <LayoutDashboard size={14} className="text-[#D4A000]" />
                        Dashboard
                      </Link>
                      <div className="my-1 border-t border-[#E8E0CC]/60" />
                      <button
                        onClick={async () => await logout.mutateAsync()}
                        disabled={logout.isPending}
                        className="flex items-center gap-2 w-full px-3 py-2.5 text-xs font-bold text-red-500 hover:bg-red-50 rounded-xl transition-colors uppercase tracking-wider disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-red-50 disabled:hover:border-red-200 disabled:hover:text-red-600"
                      >
                        {logout.isPending ? 'Logout...' : 'Logout'}
                      </button>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            ) : (
              <Link
                href="/auth/login"
                className="px-5 py-2.5 bg-[#FFD738] text-[#1C1D1F] rounded-xl text-xs font-black uppercase tracking-wider hover:bg-[#D4A000] transition-all duration-200 shadow-md shadow-[#FFD738]/30 hover:shadow-[#FFD738]/50"
              >
                JOIN MEMBER
              </Link>
            )}

            {/* Mobile Menu Button */}
            <button
              className="lg:hidden p-2.5 rounded-xl bg-white/60 backdrop-blur-sm border border-[#E8E0CC]/80 text-[#6B7280] hover:text-[#1C1D1F] transition-all shadow-sm"
              onClick={() => setIsMenuOpen(true)}
              aria-label="Open menu"
            >
              <Menu size={18} />
            </button>
          </div>
        </div>
      </header>

      {/* Mobile Menu Overlay */}
      <AnimatePresence>
        {isMenuOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsMenuOpen(false)}
              className="fixed inset-0 bg-black/20 backdrop-blur-sm z-40 lg:hidden"
            />
            <motion.div
              initial={{ opacity: 0, x: '100%' }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: '100%' }}
              transition={{ type: 'spring', damping: 25, stiffness: 200 }}
              className="fixed top-0 right-0 bottom-0 z-50 w-[300px] bg-white/90 backdrop-blur-2xl border-l border-[#E8E0CC]/80 shadow-2xl flex flex-col lg:hidden"
            >
              {/* Mobile Header */}
              <div className="p-5 flex items-center justify-between border-b border-[#E8E0CC]/60">
                <div className="flex items-center gap-3">
                  <Image src={'/logo.avif'} width={32} height={32} alt="logo" />
                  <span className="font-black text-sm uppercase tracking-wider text-[#1C1D1F]">
                    Garam <span className="text-[#D4A000]">Cap Kapal</span>
                  </span>
                </div>
                <button
                  onClick={() => setIsMenuOpen(false)}
                  className="p-2 rounded-xl bg-[#FFF9E8] border border-[#E8E0CC] text-[#6B7280] hover:text-[#1C1D1F] transition-colors"
                  aria-label="Close menu"
                >
                  <X size={18} />
                </button>
              </div>

              {/* Mobile Nav */}
              <div className="flex-1 overflow-y-auto p-4 flex flex-col gap-1">
                {NAV_ITEMS.map((item, i) => {
                  if (item.href) {
                    const isActive = isPathActive(pathname, item.href);
                    return (
                      <motion.div
                        key={item.href}
                        initial={{ opacity: 0, x: 20 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: i * 0.04 }}
                      >
                        <Link
                          href={item.href}
                          onClick={() => setIsMenuOpen(false)}
                          className={cn(
                            'flex items-center px-4 py-3.5 rounded-xl text-sm font-bold uppercase tracking-wider transition-all',
                            isActive
                              ? 'bg-[#FFD738]/15 text-[#D4A000] border border-[#FFD738]/30'
                              : 'text-[#6B7280] hover:text-[#1C1D1F] hover:bg-[#FFF9E8]'
                          )}
                        >
                          {item.label}
                        </Link>
                      </motion.div>
                    );
                  }

                  return (
                    <motion.div
                      key={item.label}
                      initial={{ opacity: 0, x: 20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: i * 0.04 }}
                      className="flex flex-col gap-1"
                    >
                      <div className="px-4 py-2 mt-2 text-[10px] font-black text-[#9CA3AF] uppercase tracking-widest">
                        {item.label}
                      </div>
                      {item.children?.map((child) => {
                        const isChildActive = isPathActive(
                          pathname,
                          child.href
                        );
                        return (
                          <Link
                            key={child.href}
                            href={child.href}
                            onClick={() => setIsMenuOpen(false)}
                            className={cn(
                              'flex items-center px-4 py-3 rounded-xl text-sm font-bold uppercase tracking-wider transition-all',
                              isChildActive
                                ? 'bg-[#FFD738]/15 text-[#D4A000] border border-[#FFD738]/30'
                                : 'text-[#6B7280] hover:text-[#1C1D1F] hover:bg-[#FFF9E8]'
                            )}
                          >
                            {child.label}
                          </Link>
                        );
                      })}
                    </motion.div>
                  );
                })}
              </div>

              {/* Mobile Footer */}
              <div className="p-4 border-t border-[#E8E0CC]/60">
                {user ? (
                  <Link
                    href={dashboardHref}
                    className="flex items-center gap-3 w-full p-3 rounded-xl bg-[#FFF9E8] border border-[#E8E0CC]"
                  >
                    <div className="w-9 h-9 bg-linear-to-br from-[#FFD738] to-[#D4A000] rounded-full flex items-center justify-center text-[#1C1D1F] font-black text-sm">
                      {user.name[0]}
                    </div>
                    <div>
                      <p className="text-xs font-bold text-[#1C1D1F]">
                        {user.name}
                      </p>
                      <p className="text-[10px] text-[#9CA3AF] font-medium">
                        Lihat Dashboard
                      </p>
                    </div>
                  </Link>
                ) : (
                  <Link
                    href="/auth/login"
                    className="w-full flex items-center justify-center py-3 bg-[#FFD738] text-[#1C1D1F] rounded-xl text-sm font-black uppercase tracking-wider hover:bg-[#D4A000] transition-colors"
                  >
                    JOIN MEMBER
                  </Link>
                )}
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </>
  );
}
