"use client";

import { useState, useRef, useEffect } from "react";
import Image from "next/image";
import {
  Menu,
  X,
  User,
  LogOut,
  LayoutDashboard,
  Boxes,
  ClipboardCheck,
  BarChart3,
  ChevronDown,
  Warehouse,
  Package,
  ArrowLeftRight,
  FileText,
  Leaf,
} from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { signIn, signOut, useSession } from "next-auth/react";

/* =====================================================
MENU CONFIG
===================================================== */
const menuConfig = [
  { name: "Dashboard", href: "/", icon: LayoutDashboard },

  {
    name: "Barang",
    icon: Package,
    children: [
      { name: "Master Items", href: "/items", icon: Boxes },
      { name: "Data mentah dari Accurate", href: "/accurate", icon: Boxes },
      { name: "Test Scan QRCode 1.4", href: "/scan", icon: Boxes },
    ],
  },

  {
    name: "Inventory",
    icon: Boxes,
    children: [
      { name: "Stok Gudang", href: "/inventory", icon: Boxes },
      { name: "Mutasi Stok", href: "/stock-movements", icon: ArrowLeftRight },
    ],
  },

  {
    name: "Transaksi",
    icon: ClipboardCheck,
    children: [
      { name: "Stock Opname", href: "/stock-opname", icon: ClipboardCheck },
      { name: "Stock Transfer (STO)", href: "/sto", icon: ArrowLeftRight },
    ],
  },

  {
    name: "Laporan",
    icon: BarChart3,
    children: [
      { name: "Stok Barang", href: "/reports/stock", icon: Boxes },
      { name: "Mutasi Stok", href: "/reports/movement", icon: ArrowLeftRight },
      { name: "Stock Opname", href: "/reports/opname", icon: FileText },
    ],
  },

  {
    name: "Master Data",
    icon: Boxes,
    children: [
      { name: "Gudang", href: "/gudang", icon: Warehouse },
      { name: "Area Gudang / Rak", href: "/location-bins", icon: Warehouse },
      { name: "Kategori", href: "/categories", icon: Boxes },
      { name: "Satuan", href: "/satuan", icon: Package },
      { name: "Supplier", href: "/suppliers", icon: Warehouse },
      { name: "User", href: "/users", icon: User }, // admin only
      { name: "Log Activity", href: "/activity-logs", icon: FileText },
    ],
  },
    {
    name: "Tutorial",
    icon: ClipboardCheck,
    children: [
      { name: "Input StockOpname", href: "/tutorial/input-stock-opname", icon: ClipboardCheck },
      { name: "Laporan StockOpname", href: "/tutorial/laporan-stock-opname", icon: ClipboardCheck },
      // { name: "Stock Transfer (STO)", href: "/sto", icon: ArrowLeftRight },
    ],
  },
];

export function Navbar() {
  const { data: session, status } = useSession();
  const [imgError, setImgError] = useState(false);
  const role = (session?.user as any)?.role || "";
  const isAdmin = role === "ADMIN";

  const [open, setOpen] = useState(false);
  const [dropdownOpen, setDropdownOpen] = useState<string | null>(null);
  const [userOpen, setUserOpen] = useState(false);

  // const dropdownRef = useRef<HTMLDivElement>(null);
  const desktopMenuRef = useRef<HTMLDivElement>(null);
  const userMenuRef = useRef<HTMLDivElement>(null);

  const pathname = usePathname();
  const router = useRouter();

  /* =====================================================
  FILTER MENU BASED ROLE
  ===================================================== */

  const filteredMenu = menuConfig.map((menu) => {
    if (!menu.children) return menu;

    return {
      ...menu,
      children: menu.children.filter((child) => {
        // ADMIN full access
      if (isAdmin) return true;

      // NON ADMIN: hide restricted routes
      const restrictedRoutes = [
        "/users",
        "/activity-logs",
        "/suppliers",
        "/gudang",
        "/satuan",
        // "/location-bins",
        "/sto",
        "/stock-movements",
      ];

      return !restrictedRoutes.includes(child.href);
      }),
    };
  });

  /* =====================================================
  ACTIVE PATH
  ===================================================== */
  const isActive = (href?: string) => {
    if (!href) return false;
    if (href === "/") return pathname === "/";
    return pathname === href || pathname.startsWith(href + "/");
  };

  const isChildActive = (children: any[]) => {
    return children.some((child: any) => isActive(child.href));
  };

  const handleNavigate = (href: string) => {
    setOpen(false);
    setDropdownOpen(null);
    setUserOpen(false);

    setTimeout(() => router.push(href), 10);
  };

  const toggleDropdown = (menuName: string) => {
  setDropdownOpen((prev) =>
    prev === menuName ? null : menuName
  );
};
const mobileMenuRef = useRef<HTMLDivElement>(null);
  /* =====================================================
  CLICK OUTSIDE
  ===================================================== */
useEffect(() => {
  function handleClickOutside(event: MouseEvent | TouchEvent) {
    const path = (event as any).composedPath?.() || [];

    const isInside = (ref: any) => {
      if (!ref?.current) return false;

      return (
        path.includes(ref.current) ||
        ref.current.contains?.(event.target as Node)
      );
    };

    const clickedInsideDesktop = isInside(desktopMenuRef);
    const clickedInsideUser = isInside(userMenuRef);
    const clickedInsideMobile = isInside(mobileMenuRef);

    // kalau klik di dalam navbar apa pun → jangan close
    if (clickedInsideDesktop || clickedInsideUser || clickedInsideMobile) {
      return;
    }

    setDropdownOpen(null);
    setUserOpen(false);
  }

  document.addEventListener("mousedown", handleClickOutside);
  document.addEventListener("touchstart", handleClickOutside);

  return () => {
    document.removeEventListener("mousedown", handleClickOutside);
    document.removeEventListener("touchstart", handleClickOutside);
  };
}, []);

  useEffect(() => {
    setOpen(false);
    setDropdownOpen(null);
    setUserOpen(false);
  }, [pathname]);

  return (
    <header className="sticky top-0 z-50">
      {/* BACKGROUND */}
      <div className="absolute inset-0 bg-linear-to-r from-green-200/40 via-emerald-100/30 to-green-300/40 blur-2xl opacity-60" />

      {/* MAIN */}
      <div className="relative backdrop-blur-xl bg-white/70 border-b border-green-100 shadow-[0_10px_40px_rgba(0,0,0,0.08)]">
        <div className="absolute inset-0 bg-linear-to-b from-white/60 to-transparent pointer-events-none" />

        <div className="relative w-full max-w-450 mx-auto px-3 md:px-6 py-3 flex items-center justify-between gap-3">
          {/* =====================================================
          LOGO
          ===================================================== */}
          <motion.div
            whileHover={{ scale: 1.01 }}
            className="flex items-center gap-3 px-3 py-2 rounded-2xl bg-linear-to-br from-white to-green-50 border border-green-100 shadow-md"
          >
            <div className="relative w-12 h-12 shrink-0 rounded-xl overflow-hidden shadow-inner">
              <Image
                src="/images/logo.png"
                alt="Logo"
                fill
                priority
                className="object-contain"
              />
            </div>

            <div>
            <p className="text-base font-bold text-green-700">
                Dsr Inventory
              </p>
              <p className="text-[10px] text-gray-500">
                Agriculture System
              </p>
            </div>
          </motion.div>

          {/* =====================================================
          DESKTOP MENU
          ===================================================== */}
        <nav
          className="hidden md:flex items-center gap-2 flex-1 justify-center"
          ref={desktopMenuRef}
        >
            {filteredMenu.map((menu) => {
              const Icon = menu.icon;

              if (!menu.children) {
                return (
                  <Link
                    key={menu.name}
                    href={menu.href!}
                    className={`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium transition
                    ${
                      isActive(menu.href)
                        ? "bg-linear-to-r from-green-600 to-emerald-500 text-white shadow-lg"
                        : "text-gray-600 hover:bg-green-50"
                    }`}
                  >
                    <Icon className="w-4 h-4" />
                    {menu.name}
                  </Link>
                );
              }

              if (menu.children.length === 0) return null;

              const activeParent = isChildActive(menu.children);

              return (
                <div key={menu.name} className="relative">
                  <button
                    onClick={() =>
                      toggleDropdown(menu.name)
                    }
                    className={`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium transition
                    ${
                      activeParent
                        ? "bg-linear-to-r from-green-600 to-emerald-500 text-white shadow-lg"
                        : "text-gray-600 hover:bg-green-50"
                    }`}
                  >
                    <Icon className="w-4 h-4" />
                    {menu.name}
                    <ChevronDown
                      className={`w-4 h-4 transition ${
                        dropdownOpen === menu.name ? "rotate-180" : ""
                      }`}
                    />
                  </button>

                  <AnimatePresence>
                    {dropdownOpen === menu.name && (
                      <motion.div
                        initial={{ opacity: 0, y: 12, scale: 0.96 }}
                        animate={{ opacity: 1, y: 0, scale: 1 }}
                        exit={{ opacity: 0, y: 10, scale: 0.96 }}
                        className="absolute top-full left-0 mt-3 w-60 rounded-2xl overflow-hidden bg-white border border-green-100 shadow-2xl"
                      >
                        <div className="p-2 space-y-1">
                          {menu.children.map((child) => {
                            const ChildIcon = child.icon;

                            return (
                              <button
                                key={child.href}
                                onClick={() => handleNavigate(child.href)}
                                className={`flex items-center gap-2 px-3 py-2 rounded-xl text-sm w-full text-left transition
                                ${
                                  isActive(child.href)
                                    ? "bg-green-100 text-green-700"
                                    : "hover:bg-green-50"
                                }`}
                              >
                                <ChildIcon className="w-4 h-4" />
                                {child.name}
                              </button>
                            );
                          })}
                        </div>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              );
            })}
          </nav>

          {/* =====================================================
          RIGHT USER SECTION
          ===================================================== */}
          <div
            className="hidden md:flex items-center gap-3"
            ref={userMenuRef}
          >
            {status === "loading" ? (
              <div className="px-4 py-2 rounded-xl bg-white border text-sm text-gray-500">
                Loading...
              </div>
            ) : session?.user ? (
              <div className="relative">
                <button
                  onClick={() => setUserOpen((prev) => !prev)}
                  className="flex items-center gap-3 px-3 py-2 rounded-2xl bg-white border border-green-100 shadow hover:shadow-md transition"
                >
                {session.user.image && !imgError ? (

                      <img
                        src={session.user.image}
                        alt="User"
                        className="w-9 h-9 rounded-xl object-cover"
                        referrerPolicy="no-referrer"
                        onError={() => setImgError(true)}
                      />
                  ) : (
                    <div className="w-9 h-9 rounded-xl bg-green-100 flex items-center justify-center">
                      <User className="w-4 h-4 text-green-700" />
                    </div>
                  )}

                  <div className="text-left leading-tight">
                    <p className="text-sm font-semibold text-gray-800 max-w-35 truncate">
                      {session.user.name}
                    </p>
                    <p className="text-[11px] text-green-700">
                      {(session.user as any).role}
                    </p>
                  </div>

                  <ChevronDown
                    className={`w-4 h-4 text-gray-500 transition ${
                      userOpen ? "rotate-180" : ""
                    }`}
                  />
                </button>

                <AnimatePresence>
                  {userOpen && (
                    <motion.div
                      initial={{ opacity: 0, y: 10, scale: 0.95 }}
                      animate={{ opacity: 1, y: 0, scale: 1 }}
                      exit={{ opacity: 0, y: 10, scale: 0.95 }}
                      className="absolute top-full right-0 mt-3 w-64 rounded-2xl bg-white border border-green-100 shadow-2xl overflow-hidden"
                    >
                      <div className="p-4 border-b bg-green-50">
                        <p className="font-semibold text-gray-800 truncate">
                          {session.user.name}
                        </p>
                        <p className="text-xs text-gray-500 truncate">
                          {session.user.email}
                        </p>
                      </div>

                      <div className="p-2 space-y-1">
                        <button
                          onClick={() => handleNavigate("/profile")}
                          className="flex items-center gap-2 px-3 py-2 rounded-xl hover:bg-green-50 text-sm w-full"
                        >
                          <User className="w-4 h-4 text-green-700" />
                          Profile
                        </button>

                        <button
                          onClick={() =>
                            signOut({
                              callbackUrl: "/login",
                            })
                          }
                          className="flex items-center gap-2 px-3 py-2 rounded-xl hover:bg-red-50 text-sm text-red-600 w-full"
                        >
                          <LogOut className="w-4 h-4" />
                          Logout
                        </button>
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            ) : (
              <button
                onClick={() =>
                  signIn("google", {
                    callbackUrl: "/",
                    prompt: "select_account",
                  })
                }
                className="px-5 py-2.5 rounded-2xl bg-linear-to-r from-green-600 to-emerald-500 text-white text-sm font-semibold shadow-lg hover:scale-[1.02] transition flex items-center gap-2"
              >
                <Leaf className="w-4 h-4" />
                Login
              </button>
            )}
          </div>

          {/* MOBILE BTN */}
         <button
            onClick={() => setOpen((prev) => !prev)}
            className="
              md:hidden
              w-12 h-12
              rounded-2xl
              bg-white
              border border-green-100
              shadow-md
              flex items-center justify-center
              active:scale-95
              transition
            "
          >
          {open ? (
              <X className="w-5 h-5 text-slate-700" />
            ) : (
              <Menu className="w-5 h-5 text-slate-700" />
            )}
          </button>
        </div>

        {/* =====================================================
        MOBILE MENU
        ===================================================== */}

     <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            transition={{ duration: 0.2 }}
            className="md:hidden px-3 pb-4"
            ref={mobileMenuRef}
            // onTouchStart={(e) => e.stopPropagation()}
            // onTouchMove={(e) => e.stopPropagation()}
            
            // ✅ IMPORTANT: stop bubbling biar scroll tidak dianggap click outside
            // onClick={(e) => e.stopPropagation()}
            // onTouchStart={(e) => e.stopPropagation()}
            // onTouchMove={(e) => e.stopPropagation()}
          >
            <div className="rounded-3xl border border-green-100 bg-white/95 backdrop-blur-xl shadow-2xl overflow-hidden h-[85vh] flex flex-col">

              {/* USER SECTION */}
              {session?.user ? (
                <div className="p-4 border-b border-slate-100 bg-linear-to-r from-emerald-50 to-white">

                  <div className="flex items-center gap-3">

                    {session.user.image && !imgError ? (
                      <img
                        src={session.user.image}
                        alt="User"
                        className="w-14 h-14 rounded-2xl object-cover border-2 border-white shadow"
                        referrerPolicy="no-referrer"
                        onError={() => setImgError(true)}
                      />
                    ) : (
                      <div className="w-14 h-14 rounded-2xl bg-emerald-100 flex items-center justify-center shadow">
                        <User className="w-6 h-6 text-emerald-700" />
                      </div>
                    )}

                    <div className="min-w-0 flex-1">
                      <div className="font-bold text-[15px] text-slate-800 truncate">
                        {session.user.name}
                      </div>

                      <div className="text-xs text-slate-500 truncate mt-0.5">
                        {session.user.email}
                      </div>

                      <div className="inline-flex mt-2 px-2.5 py-1 rounded-full bg-emerald-100 text-emerald-700 text-[11px] font-semibold">
                        {(session.user as any).role}
                      </div>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-2 mt-4">

                    <button
                      onClick={() => handleNavigate("/profile")}
                      className="flex items-center justify-center gap-2 py-3 rounded-2xl bg-white border border-slate-200 text-sm font-semibold text-slate-700 active:scale-[0.98] transition"
                    >
                      <User className="w-4 h-4" />
                      Profile
                    </button>

                    <button
                      onClick={() =>
                        signOut({
                          callbackUrl: "/login",
                        })
                      }
                      className="flex items-center justify-center gap-2 py-3 rounded-2xl bg-red-50 border border-red-100 text-sm font-semibold text-red-600 active:scale-[0.98] transition"
                    >
                      <LogOut className="w-4 h-4" />
                      Logout
                    </button>

                  </div>
                </div>
              ) : (
                <div className="p-4 border-b border-slate-100">
                  <button
                    onClick={() =>
                      signIn("google", {
                        callbackUrl: "/",
                        prompt: "select_account",
                      })
                    }
                    className="w-full flex items-center justify-center gap-2 py-3 rounded-2xl bg-linear-to-r from-emerald-600 to-green-500 text-white font-semibold shadow-lg active:scale-[0.99] transition"
                  >
                    <Leaf className="w-4 h-4" />
                    Login with Google
                  </button>
                </div>
              )}

              {/* MENU WRAPPER */}
              <div
                className="p-3 space-y-3 flex-1 overflow-y-auto overscroll-contain"
                
                // ✅ IMPORTANT: ini bikin scroll tidak dianggap click event
                // onTouchMove={(e) => e.stopPropagation()}
                 onTouchStart={(e) => e.stopPropagation()}
              >

                {filteredMenu.map((menu) => {
                  const Icon = menu.icon;

                  if (!menu.children) {
                    return (
                      <button
                        key={menu.name}
                        onClick={() => handleNavigate(menu.href!)}
                        className={`
                          w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl
                          text-left transition active:scale-[0.99]
                          ${
                            isActive(menu.href)
                              ? "bg-linear-to-r from-emerald-600 to-green-500 text-white shadow-lg"
                              : "bg-slate-50 text-slate-700 border border-slate-100"
                          }
                        `}
                      >
                        <div
                          className={`
                            w-10 h-10 rounded-xl flex items-center justify-center shrink-0
                            ${
                              isActive(menu.href)
                                ? "bg-white/20"
                                : "bg-white border border-slate-200"
                            }
                          `}
                        >
                          <Icon className="w-5 h-5" />
                        </div>

                        <div className="font-semibold text-[15px]">
                          {menu.name}
                        </div>
                      </button>
                    );
                  }

                  if (menu.children.length === 0) return null;

                  const activeParent = isChildActive(menu.children);

                  return (
                    <div
                      key={menu.name}
                      className="rounded-2xl border border-slate-100 overflow-hidden bg-white"
                    >
                      {/* PARENT */}
                      <button
                        onClick={() => toggleDropdown(menu.name)}
                        className={`
                          w-full flex items-center justify-between px-4 py-3.5 transition
                          ${
                            activeParent
                              ? "bg-emerald-50"
                              : "bg-white"
                          }
                        `}
                      >
                        <div className="flex items-center gap-3 min-w-0">

                          <div
                            className={`
                              w-10 h-10 rounded-xl flex items-center justify-center shrink-0
                              ${
                                activeParent
                                  ? "bg-emerald-100 text-emerald-700"
                                  : "bg-slate-100 text-slate-600"
                              }
                            `}
                          >
                            <Icon className="w-5 h-5" />
                          </div>

                          <div className="text-left">
                            <div className="font-bold text-[15px] text-slate-800">
                              {menu.name}
                            </div>

                            <div className="text-[11px] text-slate-500">
                              {menu.children.length} menu
                            </div>
                          </div>

                        </div>

                        <ChevronDown
                          className={`
                            w-5 h-5 text-slate-500 transition
                            ${
                              dropdownOpen === menu.name
                                ? "rotate-180"
                                : ""
                            }
                          `}
                        />
                      </button>

                      {/* CHILDREN */}
                      <AnimatePresence>
                        {dropdownOpen === menu.name && (
                          <motion.div
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            exit={{ opacity: 0 }}
                            className="overflow-hidden"
                            
                            // ✅ IMPORTANT: stop scroll bubbling
                            // onTouchMove={(e) => e.stopPropagation()}
                          >
                            <div className="px-3 pb-3 space-y-2 bg-slate-50/70">

                              {menu.children.map((child) => {
                                const ChildIcon = child.icon;

                                return (
                                  <button
                                    key={child.href}
                                    onClick={() => handleNavigate(child.href)}
                                    className={`
                                      w-full flex items-center gap-3 px-3 py-3 rounded-xl
                                      text-left transition active:scale-[0.99]
                                      ${
                                        isActive(child.href)
                                          ? "bg-emerald-600 text-white shadow"
                                          : "bg-white border border-slate-100 text-slate-700"
                                      }
                                    `}
                                  >
                                    <div
                                      className={`
                                        w-9 h-9 rounded-lg flex items-center justify-center shrink-0
                                        ${
                                          isActive(child.href)
                                            ? "bg-white/20"
                                            : "bg-slate-100"
                                        }
                                      `}
                                    >
                                      <ChildIcon className="w-4 h-4" />
                                    </div>

                                    <div className="font-medium text-sm leading-tight">
                                      {child.name}
                                    </div>
                                  </button>
                                );
                              })}

                            </div>
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </div>
                  );
                })}

              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      </div>
    </header>
  );
}