"use client";

import Link from "next/link";
import Image from "next/image";
import { usePathname, useRouter } from "next/navigation";
import { useAtom } from "jotai";
import { useEffect, useRef, useState } from "react";
import { BaseModal } from "@/components/modal";
import { useLocale, useTranslations } from "next-intl";
import DynamicButton from "@/components/button";
import LoginModal from "./loginModal";
import { loginModalAtom } from "@/components/state/loginAtom";
import { MenuSquare, X, ChevronLeft, LogOut } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { useSession, useSessionActions } from "@/auth/session-provider";
import { logout } from "@/actions/auth/logout";
import { useAppToast } from "@/app/[lang]/providers";
import NotificationDropdown from "@/components/NotificationDropdown";
import { useGeneralSettings } from "@/lib/clientQueries";
import { LangDropdown } from "@/components/languages-dropdown";

const Navbar = () => {
  const toast = useAppToast();
  const pathname = usePathname();
  const router = useRouter();
  const [loginOpen, setLoginOpen] = useAtom(loginModalAtom);
  const [hoveredMenu, setHoveredMenu] = useState<string | null>(null);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [logoutConfirmOpen, setLogoutConfirmOpen] = useState(false);
  const t = useTranslations("NAVBAR");
  const lang = useLocale();
  const isRtl = (lang || "").toLowerCase().startsWith("ar");
  const session = useSession();
  const { clearSession } = useSessionActions();
  const { data: settings, isLoading } = useGeneralSettings();
  const isFallback = Boolean((settings as any)?._isFallback);

  const isDashboard = pathname.includes("/dashboard");

  const allowDashboardExitRef = useRef(false);

  useEffect(() => {
    if (!isDashboard) return;

    // Create a guard history entry so the first Back click triggers popstate.
    try {
      window.history.pushState(null, "", window.location.href);
    } catch {
      // ignore
    }

    const handlePopState = () => {
      if (allowDashboardExitRef.current) return;

      const nextPath = window.location.pathname;
      if (!nextPath.includes("/dashboard")) {
        try {
          window.history.pushState(null, "", "/dashboard");
        } catch {
          // ignore
        }
        router.replace("/dashboard");
      }
    };

    window.addEventListener("popstate", handlePopState);
    return () => window.removeEventListener("popstate", handlePopState);
  }, [isDashboard, router]);

  const isHomePage = pathname === "/" || pathname === `/${lang}`;

  const normalizedPathname = (() => {
    if (!pathname) return "/";
    const langPrefix = `/${lang}`;
    if (pathname === langPrefix) return "/";
    if (pathname.startsWith(`${langPrefix}/`))
      return pathname.slice(langPrefix.length);
    return pathname;
  })();

  const isServicesRoute = normalizedPathname.startsWith("/services");

  const handleScroll = (id: string) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
  };

  const handleLogout = async () => {
    clearSession();
    try {
      const res = await logout();
      if (res === true) {
        toast.success(t("logout_success"));
        localStorage.removeItem("ataya_logged_in");
        // Always send the user to the localized home page after logout
        allowDashboardExitRef.current = true;
        setLogoutConfirmOpen(false);
        router.push(`/${lang}`);
      } else {
        toast.error(t("logout_failed"));
      }
    } catch (err) {
      console.error("❌ Logout error:", err);
      toast.error(t("logout_error"));
    }
  };

  const navLinks = [
    { href: "/", label: t("home") },
    {
      href: "/horses",
      label: t("horses_platform"),
      submenu: [
        { href: "/horses", label: t("offers") },
        { href: "/auctions", label: t("auctions") },
      ],
    },
    {
      href: "/camels",
      label: t("camels_platform"),
      submenu: [
        { href: "/camels", label: t("offers") },
        { href: "/camels/auctions", label: t("auctions") },
      ],
    },
    {
      href: "/annual-auctions",
      label: t("annual_auctions"),
      /* submenu: [
        { href: "/annual-auctions/horses", label: t("annual_horse_auctions") },
        {
          href: "/annual-auctions/horses/camels",
          label: t("annual_camel_auctions"),
        },
      ], */
    },
    {
      scrollTo: "services",
      label: t("services"),
      submenu: [
        { href: "/services/medical", label: t("medical_services") },
        { href: "/services/transport", label: t("transport_services") },
        { href: "/services/products", label: t("animal_products") },
      ],
    },
    /*     ...(isHomePage ? [{ scrollTo: "stats", label: t("statistics") }] : []),
     */ { href: "/contact", label: t("contact_us") },
    ...(session ? [{ href: "/dashboard", label: t("dashboard") }] : []),
  ];

  const logoutTriggerBaseClass =
    "btn-shine-effect relative overflow-hidden border border-[#dc4d4d] bg-[linear-gradient(135deg,#ef4444_0%,#dc2626_55%,#b91c1c_100%)] text-white shadow-[0_20px_40px_-24px_rgba(220,38,38,0.62)] transition-all hover:-translate-y-0.5 hover:border-[#c93535] hover:shadow-[0_24px_46px_-22px_rgba(220,38,38,0.78)]";
  const logoutTriggerDesktopClass = `${logoutTriggerBaseClass} hidden md:flex rounded-2xl px-4 py-2.5 font-semibold`;
  const logoutTriggerDashboardClass = `${logoutTriggerBaseClass} rounded-2xl px-4 py-2.5 font-semibold`;
  const logoutTriggerMobileClass = `${logoutTriggerBaseClass} w-full rounded-2xl py-3 font-semibold`;
  const logoutIconShellClass =
    "inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/25 bg-white/12 text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.18)] backdrop-blur-sm";
  const logoutCancelClass =
    "flex-1 rounded-2xl border border-[#d7e2db] bg-[linear-gradient(135deg,#ffffff_0%,#eff6f1_100%)] text-[#0F5132] shadow-[0_12px_24px_-22px_rgba(15,81,50,0.45)] hover:-translate-y-0.5 hover:border-[#0F5132]/25 hover:bg-[#f8fbf8]";
  const logoutConfirmClass =
    "flex-1 rounded-2xl border border-[#dc4d4d] bg-[linear-gradient(135deg,#ef4444_0%,#dc2626_55%,#b91c1c_100%)] text-white shadow-[0_20px_36px_-24px_rgba(220,38,38,0.68)] hover:-translate-y-0.5 hover:border-[#c93535] hover:text-white";
  const logoutModal = (
    <BaseModal
      isOpen={logoutConfirmOpen}
      contentClassName="w-full max-w-[430px] h-fit rounded-[28px] border border-[#e5ece8] bg-[linear-gradient(180deg,#ffffff_0%,#f8fbf9_100%)] shadow-[0_32px_70px_-38px_rgba(15,81,50,0.35)]"
      onClose={() => setLogoutConfirmOpen(false)}
      placement="center"
      title={t("logout")}
    >
      <div className="space-y-5" dir={isRtl ? "rtl" : "ltr"}>
        <div
          className={`flex items-center gap-3 ${
            isRtl ? "text-right" : "text-left"
          }`}
        >
          <div className="flex h-12 w-12 items-center justify-center rounded-2xl border border-[#fecaca] bg-[linear-gradient(135deg,#fff5f5_0%,#fee2e2_100%)] text-[#dc2626] shadow-[0_18px_30px_-24px_rgba(220,38,38,0.45)]">
            <LogOut className="h-5 w-5" />
          </div>
          <div className="space-y-1">
            <p className="text-base font-extrabold text-[#123B28]">
              {t("logout")}
            </p>
            <p className="text-xs text-slate-500">
              {isRtl
                ? "سيتم إنهاء جلستك الحالية والعودة إلى الواجهة الرئيسية."
                : "Your current session will end and you will return to the main page."}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-3">
          <DynamicButton
            variant="bordered"
            radius="lg"
            className={logoutCancelClass}
            onClick={() => setLogoutConfirmOpen(false)}
          >
            {t("cancel")}
          </DynamicButton>
          <DynamicButton
            radius="lg"
            startContent={<LogOut className="h-4 w-4" />}
            className={logoutConfirmClass}
            onClick={async () => {
              await handleLogout();
              setLogoutConfirmOpen(false);
            }}
          >
            {t("confirm")}
          </DynamicButton>
        </div>
      </div>
    </BaseModal>
  );

  if (isDashboard) {
    return (
      <>
        <div className="h-16" />
        <header className="fixed top-0 inset-x-0 z-50 bg-white shadow-sm transition-all duration-300 ease-in-out transform hover:scale-105 hover:shadow-lg">
          <div className="max-w-7xl mx-auto flex items-center justify-between px-4 py-1 ">
            <Link
              href="/"
              onClick={() => {
                allowDashboardExitRef.current = true;
              }}
              className="flex flex-col items-center"
            >
              <Image
                src={
                  settings?.colored_logo ||
                  settings?.main_logo ||
                  (isFallback ? "/logo.png" : "/logo.png")
                }
                alt="Logo"
                width={200}
                height={50}
                className="h-12 w-auto object-contain transition-transform duration-300 hover:scale-110"
                priority
              />
              <span className="text-base font-bold text-green-800">
                {settings?.site_name
                  ? String(settings.site_name)
                  : isFallback
                    ? t("app_name")
                    : ""}
              </span>
            </Link>

            <div className="flex items-center gap-3">
              <NotificationDropdown />

              <LangDropdown />

              {session && (
                <DynamicButton
                  onClick={() => setLogoutConfirmOpen(true)}
                  startContent={
                    <span className={logoutIconShellClass}>
                      <LogOut className="h-4 w-4" />
                    </span>
                  }
                  className={logoutTriggerDashboardClass}
                >
                  {t("logout")}
                </DynamicButton>
              )}
            </div>
          </div>

          {logoutModal}
        </header>
      </>
    );
  }

  return (
    <header className="sticky top-0 z-50 bg-white border-b border-gray-200">
      <div className="max-w-7xl mx-auto flex items-center justify-between px-4 py-2 md:py-3">
        <Link href="/" className="flex flex-col items-center">
          {isLoading ? (
            <div className="flex flex-col items-center gap-2">
              <div className="h-10 w-40 bg-slate-200 rounded animate-pulse" />
              <div className="h-4 w-24 bg-slate-200 rounded animate-pulse" />
            </div>
          ) : (
            <>
              <Image
                src={
                  settings?.colored_logo ||
                  settings?.main_logo ||
                  (isFallback ? "/logo.png" : "/logo.png")
                }
                alt="Logo"
                width={160}
                height={40}
                className="h-10 w-auto object-contain"
                priority
              />
              <span className="text-sm font-bold text-green-800">
                {settings?.site_name
                  ? String(settings.site_name)
                  : isFallback
                    ? t("app_name")
                    : ""}
              </span>
            </>
          )}
        </Link>

        <nav className="hidden md:flex items-center gap-1 relative">
          {navLinks.map(({ href, label, submenu, scrollTo }) => (
            <div
              key={label}
              className="relative group"
              onMouseEnter={() => submenu && setHoveredMenu(label)}
              onMouseLeave={() => submenu && setHoveredMenu(null)}
            >
              {scrollTo ? (
                <button
                  onClick={() => handleScroll(scrollTo)}
                  className={`nav-link px-3 py-2 rounded-lg text-sm font-medium ${
                    isServicesRoute ? "text-primary active" : "text-gray-700"
                  }`}
                >
                  {label}
                </button>
              ) : (
                <Link
                  href={href || "#"}
                  className={`nav-link px-3 py-2 rounded-lg text-sm font-medium ${
                    pathname === href ? "text-primary active" : "text-gray-700"
                  }`}
                >
                  {label}
                </Link>
              )}

              {submenu && hoveredMenu === label && (
                <div className="nav-dropdown absolute top-full left-0 mt-1 w-52 bg-white rounded-xl shadow-xl border border-gray-100 overflow-hidden py-1">
                  {submenu.map((subItem) => (
                    <Link
                      key={subItem.href}
                      href={subItem.href}
                      className="nav-dropdown-item block px-4 py-2.5 text-sm text-gray-700 hover:text-primary transition-all"
                    >
                      {subItem.label}
                    </Link>
                  ))}
                </div>
              )}
            </div>
          ))}
        </nav>

        <div className="flex items-center gap-3" dir="ltr">
          <button
            className="md:hidden p-2.5 rounded-xl text-primary border border-gray-200 hover:bg-gray-50 hover:border-primary/30 transition-all"
            onClick={() => setMobileOpen(true)}
          >
            <MenuSquare className="w-5 h-5" />
          </button>

          {session ? (
            <DynamicButton
              onClick={() => setLogoutConfirmOpen(true)}
              startContent={
                <span className={logoutIconShellClass}>
                  <LogOut className="h-4 w-4" />
                </span>
              }
              className={logoutTriggerDesktopClass}
            >
              {t("logout")}
            </DynamicButton>
          ) : (
            <DynamicButton
              onClick={() => setLoginOpen(true)}
              className="btn-shine-effect relative hidden md:flex items-center justify-center rounded-xl px-5 py-2 text-white btn-primary-gradient shadow-sm hover:shadow-lg transition-all"
            >
              {t("login")}
            </DynamicButton>
          )}

          <LangDropdown />

          <NotificationDropdown />
        </div>
      </div>

      {logoutModal}

      <LoginModal open={loginOpen} onClose={() => setLoginOpen(false)} />

      <AnimatePresence>
        {mobileOpen && (
          <>
            {/* Backdrop with fade animation */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.3, ease: "easeOut" }}
              className="fixed inset-0 bg-black/50 backdrop-blur-sm z-40"
              onClick={() => setMobileOpen(false)}
            />

            {/* Sidebar with slide animation */}
            <motion.aside
              initial={{ x: "100%" }}
              animate={{ x: 0 }}
              exit={{ x: "100%" }}
              transition={{ type: "spring", damping: 30, stiffness: 300 }}
              className="fixed top-0 right-0 z-50 w-72 h-full bg-white shadow-2xl flex flex-col overflow-hidden"
              style={{ direction: "rtl" }}
            >
              {/* Header */}
              <motion.div
                initial={{ opacity: 0, y: -20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.1, duration: 0.3 }}
                className="flex items-center justify-between px-5 py-4 border-b border-gray-100 bg-gradient-to-l from-[#0F5132]/5 to-transparent"
              >
                <h3 className="text-lg font-bold text-[#0F5132]">
                  {t("menu")}
                </h3>
                <motion.button
                  whileHover={{ scale: 1.1, rotate: 90 }}
                  whileTap={{ scale: 0.9 }}
                  onClick={() => setMobileOpen(false)}
                  className="p-2 rounded-full bg-gray-100 hover:bg-gray-200 transition-colors"
                >
                  <X className="w-5 h-5 text-gray-600" />
                </motion.button>
              </motion.div>

              {/* Navigation with staggered animations */}
              <nav className="flex-1 overflow-y-auto overscroll-contain py-3">
                <motion.div
                  initial="hidden"
                  animate="visible"
                  variants={{
                    hidden: {},
                    visible: {
                      transition: {
                        staggerChildren: 0.05,
                        delayChildren: 0.15,
                      },
                    },
                  }}
                  className="flex flex-col"
                >
                  {navLinks.map(({ href, label, submenu, scrollTo }, index) => (
                    <motion.div
                      key={label}
                      variants={{
                        hidden: { opacity: 0, x: 30 },
                        visible: {
                          opacity: 1,
                          x: 0,
                          transition: { duration: 0.3 },
                        },
                      }}
                      className="flex flex-col"
                    >
                      {scrollTo ? (
                        <motion.button
                          whileTap={{
                            scale: 0.98,
                            backgroundColor: "rgba(15, 81, 50, 0.05)",
                          }}
                          onClick={() => {
                            handleScroll(scrollTo);
                            setMobileOpen(false);
                          }}
                          className="flex items-center justify-between px-5 py-3.5 text-gray-800 text-sm font-semibold text-right hover:bg-[#0F5132]/5 transition-colors"
                        >
                          <span>{label}</span>
                          <ChevronLeft className="w-4 h-4 text-gray-400" />
                        </motion.button>
                      ) : (
                        <Link
                          href={href || "#"}
                          onClick={() => setMobileOpen(false)}
                        >
                          <motion.div
                            whileTap={{
                              scale: 0.98,
                              backgroundColor: "rgba(15, 81, 50, 0.05)",
                            }}
                            className={`flex items-center justify-between px-5 py-3.5 text-sm font-semibold transition-colors ${
                              pathname === href
                                ? "text-[#0F5132] bg-[#0F5132]/10 border-r-3 border-[#0F5132]"
                                : "text-gray-800 hover:bg-[#0F5132]/5"
                            }`}
                          >
                            <span>{label}</span>
                            <ChevronLeft className="w-4 h-4 text-gray-400" />
                          </motion.div>
                        </Link>
                      )}

                      {/* Submenu with nested animation */}
                      {submenu && (
                        <motion.div
                          initial={{ height: 0, opacity: 0 }}
                          animate={{ height: "auto", opacity: 1 }}
                          transition={{ duration: 0.2 }}
                          className="bg-gray-50/80 border-y border-gray-100"
                        >
                          {submenu.map((subItem) => (
                            <Link
                              key={subItem.href}
                              href={subItem.href}
                              onClick={() => setMobileOpen(false)}
                            >
                              <motion.div
                                whileTap={{ scale: 0.98 }}
                                className={`px-8 py-2.5 text-[13px] transition-colors ${
                                  pathname === subItem.href
                                    ? "text-[#0F5132] font-semibold"
                                    : "text-gray-600 hover:text-[#0F5132]"
                                }`}
                              >
                                {subItem.label}
                              </motion.div>
                            </Link>
                          ))}
                        </motion.div>
                      )}
                    </motion.div>
                  ))}
                </motion.div>
              </nav>

              {/* Footer with slide up animation */}
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.3, duration: 0.3 }}
                className="p-4 border-t border-gray-100 bg-gray-50/50"
              >
                {session ? (
                  <motion.div whileTap={{ scale: 0.98 }}>
                    <DynamicButton
                      onClick={() => {
                        setMobileOpen(false);
                        setLogoutConfirmOpen(true);
                      }}
                      startContent={
                        <span className={logoutIconShellClass}>
                          <LogOut className="h-4 w-4" />
                        </span>
                      }
                      className={logoutTriggerMobileClass}
                    >
                      {t("logout")}
                    </DynamicButton>
                  </motion.div>
                ) : (
                  <motion.div whileTap={{ scale: 0.98 }}>
                    <DynamicButton
                      onClick={() => {
                        setMobileOpen(false);
                        setLoginOpen(true);
                      }}
                      className="w-full rounded-xl text-white py-3 btn-primary-gradient shadow-md font-semibold"
                    >
                      {t("login")}
                    </DynamicButton>
                  </motion.div>
                )}
              </motion.div>
            </motion.aside>
          </>
        )}
      </AnimatePresence>
    </header>
  );
};

export default Navbar;
