"use client";

import { useLogoutMutation } from "@/api/auth.api";
import { useAppSelector } from "@/redux/hooks";
import { AnimatePresence, motion } from "framer-motion";
import {
  BookOpen,
  ChevronDown,
  CircleUserRound,
  Globe,
  LogOut,
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import Notifications from "./Notifications";
import AskQuestionModal from "./AskQuestionModal";
import SubscriptionRequiredModal from "./Membership/SubscriptionRequiredModal";

const LANGUAGES: { code: string; label: string }[] = [
  { code: "en", label: "English" },
  { code: "ar", label: "عربي" },
];

function LangDropdown() {
  const [open, setOpen] = useState(false);
  const [lang, setLang] = useState("en");
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node))
        setOpen(false);
    }
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, []);

  const current = LANGUAGES.find((l) => l.code === lang)!;

  return (
    <div ref={ref} className="relative ml-5">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="font-sans flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-[#e5e7eb] bg-white hover:border-[#d1d5db] transition-colors text-sm text-[#4b5563] font-medium shadow-sm"
      >
        <Globe className="h-3.5 w-3.5 text-[#9ca3af] shrink-0" />
        <span>{current.code.toUpperCase()}</span>
        <ChevronDown
          className={`h-3.5 w-3.5 text-[#9ca3af] transition-transform ${open ? "rotate-180" : ""}`}
        />
      </button>
      {open && (
        <div className="absolute left-0 top-full mt-1.5 w-36 bg-white border border-[#e5e7eb] rounded-xl shadow-lg z-50 overflow-hidden">
          {LANGUAGES.map((l) => (
            <button
              key={l.code}
              type="button"
              onClick={() => {
                setLang(l.code);
                setOpen(false);
              }}
              className={`w-full flex items-center justify-between px-4 py-2.5 text-sm transition-colors ${
                l.code === lang
                  ? "bg-blue-50 text-blue-600 font-semibold"
                  : "text-[#374151] hover:bg-[#f9fafb]"
              }`}
            >
              <span>{l.label}</span>
              {l.code === lang && (
                <svg
                  className="h-3.5 w-3.5 text-blue-500"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2.5}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M5 13l4 4L19 7"
                  />
                </svg>
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

const AVATAR_COLOR = "#0ea5e9";

function getInitials(name?: string | null): string {
  if (!name) return "U";
  const parts = name.trim().split(/\s+/);
  if (parts.length === 0) return "U";
  const first = parts[0]?.[0] ?? "";
  const second = parts.length > 1 ? (parts[parts.length - 1]?.[0] ?? "") : "";
  return (first + second).toUpperCase() || "U";
}

type AvatarUser = {
  name?: string | null;
  profileImage?: string | null;
} | null;

function Avatar({ user }: { user: AvatarUser }) {
  const initials = getInitials(user?.name);
  if (
    typeof user?.profileImage === "string" &&
    user.profileImage.trim() !== ""
  ) {
    return (
      <Image
        src={user.profileImage}
        alt={user?.name || "User"}
        width={36}
        height={36}
        className="!h-9 !w-9 rounded-full object-cover border border-[#e5e7eb]"
      />
    );
  }
  return (
    <div
      className="h-9 w-9 rounded-full flex items-center justify-center text-white text-xs font-bold border border-[#e5e7eb]"
      style={{ backgroundColor: AVATAR_COLOR }}
    >
      {initials}
    </div>
  );
}

type UserType = {
  name?: string | null;
  rankName?: string | null;
  profileImage?: string | null;
} | null;

function UserMenu({
  user,
  isOpen,
  setIsOpen,
  onLogout,
}: {
  user: UserType;
  isOpen: boolean;
  setIsOpen: (v: boolean) => void;
  onLogout: () => void;
}) {
  return (
    <div className="relative user-profile-container">
      <button
        type="button"
        className="flex items-center gap-2 group"
        aria-label="User menu"
        onClick={(e) => {
          e.stopPropagation();
          setIsOpen(!isOpen);
        }}
      >
        <Avatar user={user} />
        <ChevronDown
          className={`h-3.5 w-3.5 text-[#9ca3af] transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`}
        />
      </button>

      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 10 }}
            className="absolute right-0 top-full mt-2 w-52 bg-white rounded-2xl shadow-xl border border-[#e5e7eb] overflow-hidden z-40"
          >
            <div className="px-4 py-3 border-b border-[#e5e7eb] flex items-center gap-3">
              <Avatar user={user} />
              <div className="min-w-0">
                <p className="text-sm font-semibold text-[#111827] truncate">
                  {user?.name || "User"}
                </p>
                <p className="text-xs text-[#9ca3af] truncate">
                  {user?.rankName || ""}
                </p>
              </div>
            </div>
            <div className="py-1">
              <Link
                href="/my-account"
                onClick={() => setIsOpen(false)}
                className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-[#374151] hover:bg-[#f9fafb] transition-colors text-left no-underline"
              >
                <CircleUserRound className="h-4 w-4 text-[#9ca3af] shrink-0" />
                My Account
              </Link>
              <Link
                href="/content"
                onClick={() => setIsOpen(false)}
                className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-[#374151] hover:bg-[#f9fafb] transition-colors text-left no-underline"
              >
                <BookOpen className="h-4 w-4 text-[#9ca3af] shrink-0" />
                My Content
              </Link>
            </div>
            <div className="border-t border-[#e5e7eb] py-1">
              <button
                type="button"
                className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-red-500 hover:bg-red-50 transition-colors text-left"
                onClick={() => {
                  setIsOpen(false);
                  onLogout();
                }}
              >
                <LogOut className="h-4 w-4 shrink-0" />
                Log out
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

export default function Navbar() {
  const router = useRouter();
  const { user, isAuthenticated } = useAppSelector((state) => state.auth);
  const [logoutUser] = useLogoutMutation();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isUserDropdownOpen, setIsUserDropdownOpen] = useState(false);
  const [isAskModalOpen, setIsAskModalOpen] = useState(false);
  const [isSubModalOpen, setIsSubModalOpen] = useState(false);

  const handleLogout = async () => {
    await logoutUser();
    router.push("/");
  };

  // Asking a question requires an active subscription. Non-premium users get the
  // subscription prompt instead of the ask-a-question form.
  const handleAskQuestion = () => {
    if (user?.isPremium) {
      setIsAskModalOpen(true);
    } else {
      setIsSubModalOpen(true);
    }
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (isUserDropdownOpen && !target.closest(".user-profile-container")) {
        setIsUserDropdownOpen(false);
      }
    };
    if (isUserDropdownOpen) {
      document.addEventListener("click", handleClickOutside);
    }
    return () => document.removeEventListener("click", handleClickOutside);
  }, [isUserDropdownOpen]);

  // Lock background scroll while the mobile menu overlay is open, then restore
  // whatever overflow the page had before.
  useEffect(() => {
    if (!isMobileMenuOpen) return;
    const original = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = original;
    };
  }, [isMobileMenuOpen]);

  const pathname = usePathname();

  // A nav item is active when the current path matches its href. SeaQA also
  // covers the question discussion pages (/discussion/...).
  const isActive = (href: string): boolean => {
    if (href === "/questions") {
      return (
        pathname.startsWith("/questions") || pathname.startsWith("/discussion")
      );
    }
    return pathname === href || pathname.startsWith(`${href}/`);
  };

  const navLinkClass = (href: string) =>
    `font-sans text-sm transition-colors ${
      isActive(href)
        ? "text-blue-500 font-semibold"
        : "font-medium text-[#4b5563] hover:text-blue-500"
    }`;

  const overlayVariants = {
    hidden: { x: "100%", opacity: 0.5 },
    visible: {
      x: 0,
      opacity: 1,
      transition: {
        type: "spring",
        damping: 30,
        stiffness: 250,
        staggerChildren: 0.08,
        delayChildren: 0.15,
      },
    },
    exit: {
      x: "100%",
      opacity: 0,
      transition: {
        type: "spring",
        damping: 35,
        stiffness: 300,
        when: "afterChildren",
      },
    },
  } as const;

  const itemVariants = {
    hidden: { opacity: 0, x: 30 },
    visible: {
      opacity: 1,
      x: 0,
      transition: { duration: 0.5, ease: [0.25, 1, 0.5, 1] },
    },
    exit: {
      opacity: 0,
      x: 20,
      transition: { duration: 0.3, ease: "easeIn" },
    },
  } as const;

  return (
    <>
      <header className="fixed top-0 left-0 right-0 z-50 bg-white border-b border-[#e5e7eb] flex items-center h-16 sm:pl-14 sm:pr-8 pl-4 pr-4">
        {/* Logo */}
        <Link href="/" className="shrink-0">
          <Image
            src="/assets/images/logo-blue.svg"
            alt="MySeaTime Logo"
            width={152}
            height={45}
            className="h-11 w-auto object-contain"
          />
        </Link>

        {/* Language dropdown */}
        {/* <div className="hidden lg:block">
          <LangDropdown />
        </div> */}

        {/* Spacer */}
        <div className="flex-1" />

        {/* Desktop nav links */}
        <nav className="hidden lg:flex items-center gap-8 mr-10">
          <Link href="/blog" className={navLinkClass("/blog")}>
            Blogs
          </Link>
          <Link href="/questions" className={navLinkClass("/questions")}>
            SeaQA
          </Link>

          <Link href="/connections" className={navLinkClass("/connections")}>
            Connections
          </Link>

          <Link href="/contact-us" className={navLinkClass("/contact-us")}>
            Contact
          </Link>
        </nav>

        {/* Desktop auth */}
        <div className="hidden lg:flex items-center gap-3">
          {isAuthenticated ? (
            <>
              <button
                type="button"
                onClick={handleAskQuestion}
                className="font-sans px-5 py-2 rounded-full bg-blue-500 hover:bg-blue-600 text-white text-sm font-semibold transition-colors shadow-sm"
              >
                Ask a Question
              </button>

              <Notifications isLightPage={true} />

              {/* User dropdown */}
              <UserMenu
                user={user}
                isOpen={isUserDropdownOpen}
                setIsOpen={setIsUserDropdownOpen}
                onLogout={handleLogout}
              />
            </>
          ) : (
            <>
              <Link
                href="/login?redirect=/my-account"
                className="font-sans px-5 py-2 rounded-full text-sm font-semibold text-[#374151] border border-[#e5e7eb] hover:bg-[#f9fafb] transition-colors"
              >
                Log in
              </Link>
              <Link
                href="/signup?redirect=/my-account"
                className="font-sans px-5 py-2 rounded-full text-sm font-semibold text-white bg-blue-500 hover:bg-blue-600 transition-colors shadow-sm"
              >
                Register
              </Link>
            </>
          )}
        </div>
        {isAuthenticated && (
          <div className=" lg:hidden ml-5">
            <Notifications isLightPage={true} />
          </div>
        )}
        {/* Mobile hamburger */}
        <div className="lg:hidden flex items-center">
          <button
            onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
            className="hover:opacity-80 transition-opacity p-2"
          >
            <Image
              src={
                isMobileMenuOpen
                  ? "/assets/icons/close-dark.svg"
                  : "/assets/icons/menu-dark.svg"
              }
              alt={isMobileMenuOpen ? "Close menu" : "Open menu"}
              width={24}
              height={24}
            />
          </button>
        </div>
      </header>

      {/* Mobile menu overlay */}
      <AnimatePresence>
        {isMobileMenuOpen && (
          <motion.div
            initial="hidden"
            animate="visible"
            exit="exit"
            variants={overlayVariants}
            className="fixed inset-0 z-40 bg-white pt-16 flex flex-col lg:hidden font-sans"
          >
            <div className="flex flex-col p-6 gap-6 w-full h-full overflow-y-auto">
              {isAuthenticated && (
                <motion.div
                  variants={itemVariants}
                  className="flex items-center gap-3"
                >
                  <Avatar user={user} />
                  <div>
                    <p className="text-sm font-semibold text-[#111827]">
                      {user?.name || "User"}
                    </p>
                    <p className="text-xs text-[#9ca3af]">
                      {user?.rankName || ""}
                    </p>
                  </div>
                </motion.div>
              )}
              <motion.div variants={itemVariants}>
                <Link
                  href="/blog"
                  onClick={() => setIsMobileMenuOpen(false)}
                  className={navLinkClass("/blog")}
                >
                  Blogs
                </Link>
              </motion.div>
              <motion.div variants={itemVariants}>
                <Link
                  href="/questions"
                  onClick={() => setIsMobileMenuOpen(false)}
                  className={navLinkClass("/questions")}
                >
                  SeaQA
                </Link>
              </motion.div>

              <motion.div variants={itemVariants}>
                <Link
                  href="/connections"
                  onClick={() => setIsMobileMenuOpen(false)}
                  className={navLinkClass("/connections")}
                >
                  Connections
                </Link>
              </motion.div>

              <motion.div variants={itemVariants}>
                <Link
                  href="/contact-us"
                  onClick={() => setIsMobileMenuOpen(false)}
                  className={navLinkClass("/contact-us")}
                >
                  Contact
                </Link>
              </motion.div>

              {/* <motion.div
                variants={itemVariants}
                className="h-px bg-gray-100 w-full"
              /> */}

              {isAuthenticated ? (
                <div className="flex flex-col gap-4">
                  {/* <motion.div
                    variants={itemVariants}
                    className="flex items-center gap-3"
                  >
                    <Avatar user={user} />
                    <div>
                      <p className="text-sm font-semibold text-[#111827]">
                        {user?.name || "User"}
                      </p>
                      <p className="text-xs text-[#9ca3af]">
                        {user?.rankName || ""}
                      </p>
                    </div>
                  </motion.div> */}
                  <motion.div variants={itemVariants}>
                    <button
                      type="button"
                      onClick={() => {
                        setIsMobileMenuOpen(false);
                        handleAskQuestion();
                      }}
                      className="font-sans w-full bg-blue-500 hover:bg-blue-600 text-white px-5 py-2.5 rounded-full text-sm font-semibold transition-colors text-center block shadow-sm"
                    >
                      Ask a Question
                    </button>
                  </motion.div>
                  <motion.div variants={itemVariants}>
                    <Link
                      href="/my-account"
                      onClick={() => setIsMobileMenuOpen(false)}
                      className="font-sans w-full border border-[#e5e7eb] px-5 py-2.5 rounded-full text-sm font-semibold text-[#374151] hover:bg-[#f9fafb] transition-colors text-center block"
                    >
                      My Account
                    </Link>
                  </motion.div>
                  <motion.div variants={itemVariants}>
                    <Link
                      href="/content"
                      onClick={() => setIsMobileMenuOpen(false)}
                      className="font-sans w-full border border-[#e5e7eb] px-5 py-2.5 rounded-full text-sm font-semibold text-[#374151] hover:bg-[#f9fafb] transition-colors text-center block"
                    >
                      My Content
                    </Link>
                  </motion.div>
                  <motion.div variants={itemVariants}>
                    <button
                      onClick={() => {
                        setIsMobileMenuOpen(false);
                        handleLogout();
                      }}
                      className="font-sans w-full border border-[#e5e7eb] px-5 py-2.5 rounded-full text-sm font-semibold text-red-500 hover:bg-red-50 transition-colors text-center"
                    >
                      Log out
                    </button>
                  </motion.div>
                </div>
              ) : (
                <div className="flex flex-col gap-3 pb-6">
                  <motion.div variants={itemVariants} className="flex-1">
                    <Link
                      href="/login?redirect=/my-account"
                      onClick={() => setIsMobileMenuOpen(false)}
                      className="font-sans w-full border border-[#e5e7eb] px-5 py-2.5 rounded-full text-sm font-semibold text-[#374151] hover:bg-[#f9fafb] transition-colors text-center block"
                    >
                      Log in
                    </Link>
                  </motion.div>
                  <motion.div variants={itemVariants} className="flex-1">
                    <Link
                      href="/signup?redirect=/my-account"
                      onClick={() => setIsMobileMenuOpen(false)}
                      className="font-sans w-full bg-blue-500 hover:bg-blue-600 text-white px-5 py-2.5 rounded-full text-sm font-semibold transition-colors text-center block shadow-sm"
                    >
                      Register
                    </Link>
                  </motion.div>
                </div>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Ask a Question modal */}
      <AskQuestionModal
        open={isAskModalOpen}
        onClose={() => setIsAskModalOpen(false)}
      />

      {/* Subscription prompt for non-premium users */}
      <SubscriptionRequiredModal
        isOpen={isSubModalOpen}
        onClose={() => setIsSubModalOpen(false)}
        onViewPlans={() => {
          setIsSubModalOpen(false);
          router.push(
            `/my-account?current-section=subscription&redirect=${encodeURIComponent(
              pathname,
            )}`,
          );
        }}
      />
    </>
  );
}
