"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import mbhsLogo from "@/public/images/mbhs-logo.png";
import FlagIcon from "@/components/ui/FlagIcon";
import { useTranslations, useLocale } from "next-intl";
import { Link, useRouter, usePathname } from "@/i18n/navigation";
import { useSearchParams } from "next/navigation";
import { isAuthenticated, getUserDataCookie, clearAuthCookies, type UserData } from "@/lib/cookies";
import { instance } from "@/config/axios";

export default function Header() {
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userData, setUserData] = useState<UserData | null>(null);
  const [isScrolled, setIsScrolled] = useState(false);
  const t = useTranslations("nav");
  const locale = useLocale();
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    // Check authentication status on mount and when pathname changes.
    // Cookie state is client-only, so it must be synced after mount to avoid
    // an SSR hydration mismatch — this setState-in-effect is intentional.
    const loggedIn = isAuthenticated();
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setIsLoggedIn(loggedIn);
    setUserData(getUserDataCookie());

    // Stale-cookie guard: mbhs_user_data lives 7 days, but the HttpOnly
    // access_token may have expired server-side. Verify silently; on 401,
    // clean up so the button correctly shows "Sign In" instead of linking
    // to a protected dashboard route. _skipAuthRedirect prevents the axios
    // interceptor from force-redirecting visitors off the landing page.
    if (loggedIn) {
      instance
        .get('/v1/profile', { _skipAuthRedirect: true } as never)
        .catch((err) => {
          if (err?.response?.status === 401) {
            clearAuthCookies();
            setIsLoggedIn(false);
            setUserData(null);
          }
        });
    }
  }, [pathname]);

  // Scroll detection - change header style when white section reaches the header
  // On non-home pages (no hero), always show solid header
  useEffect(() => {
    const isHomePage = pathname === "/";

    if (!isHomePage) {
      // Non-home pages have no hero, so the header is always solid. Scroll
      // state is client-only; setting it here post-mount is intentional.
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setIsScrolled(true);
      return;
    }

    const handleScroll = () => {
      // Hero section is 100vh, header height is 64px (h-16)
      // Trigger when white section touches the bottom of the header
      const heroHeight = window.innerHeight;
      const headerHeight = 64;
      setIsScrolled(window.scrollY > heroHeight - headerHeight);
    };

    // Check initial scroll position
    handleScroll();

    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, [pathname]);

  // Sync locale with localStorage for API calls
  useEffect(() => {
    if (typeof window !== "undefined") {
      localStorage.setItem("lang", locale);
    }
  }, [locale]);

  const toggleLanguage = () => {
    const newLocale = locale === "en" ? "es" : "en";

    // Preserve all query parameters when changing language
    const queryString = searchParams.toString();
    const pathnameWithQuery = queryString ? `${pathname}?${queryString}` : pathname;

    router.replace(pathnameWithQuery, { locale: newLocale });
  };

  // Get dashboard route based on user role
  const getDashboardRoute = () => {
    if (!userData) return "/individual";

    switch (userData.role?.toLowerCase()) {
      case "admin":
        return "/admin";
      case "practice_manager":
      case "practice-manager":
        return "/practice-manager/dashboard";
      case "practitioner":
        return userData.subscription_type === 'group'
          ? "/practice-manager/dashboard"
          : "/practitioner";
      case "individual":
      default:
        return "/individual";
    }
  };

  const navLinks = [
    { name: t("home"), href: "/" },
    { name: t("about"), href: "/#about" },
    { name: t("pricing"), href: "/#pricing" },
    { name: t("testimonials"), href: "/#testimonials" },
    { name: t("faqs"), href: "/#faq" },
    { name: t("contact"), href: "/contact" },
  ];

  // Handle click for links - scroll to top/section if already on home page
  const handleLinkClick = (e: React.MouseEvent, href: string) => {
    // If clicking Home while on home page, scroll to top
    if (href === "/" && pathname === "/") {
      e.preventDefault();
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }

    // If clicking an anchor link while on home page, scroll to section
    if (href.startsWith("/#") && pathname === "/") {
      e.preventDefault();
      const sectionId = href.replace("/#", "");
      const section = document.getElementById(sectionId);
      if (section) {
        section.scrollIntoView({ behavior: "smooth" });
      }
    }
  };

  return (
    <header
      className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${
        isScrolled
          ? "bg-white shadow-md"
          : ""
      }`}
      style={!isScrolled ? { backgroundColor: 'rgba(0, 0, 0, 0.3)', backdropFilter: 'blur(10px)' } : {}}
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          {/* Logo */}
          <Link href="/" onClick={(e) => handleLinkClick(e, "/")} className="flex items-center gap-2 cursor-pointer">
            <Image src={mbhsLogo} alt="MBHS" width={40} height={40} className="rounded-lg" priority />
            <span className={`text-2xl font-extrabold transition-colors duration-300 ${isScrolled ? "text-gray-900" : "text-white"}`}>MBHS</span>
          </Link>

          {/* Desktop Navigation */}
          <nav className="hidden md:flex items-center gap-8">
            {navLinks.map((link) => (
              <Link
                key={link.name}
                href={link.href}
                onClick={(e) => handleLinkClick(e, link.href)}
                className={`text-sm font-medium transition-colors duration-300 cursor-pointer ${
                  isScrolled
                    ? "text-gray-600 hover:text-gray-900"
                    : "text-white/80 hover:text-white"
                }`}
              >
                {link.name}
              </Link>
            ))}
          </nav>

          {/* Right Side */}
          <div className="hidden md:flex items-center gap-4">
            {/* Language Toggle */}
            <button
              onClick={toggleLanguage}
              aria-label={t("changeLanguage")}
              className={`flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg transition-colors duration-300 cursor-pointer ${
                isScrolled
                  ? "text-gray-600 hover:text-gray-900 hover:bg-gray-100"
                  : "text-white/80 hover:text-white hover:bg-white/10"
              }`}
            >
              <FlagIcon locale={locale as "en" | "es"} />
              <span className="font-medium">{locale.toUpperCase()}</span>
            </button>

            {/* Sign In / Dashboard Button */}
            <Link
              href={isLoggedIn ? getDashboardRoute() : "/login"}
              className="px-5 py-2 bg-[#3B9EC9] hover:bg-[#2D8AB5] text-white text-sm font-medium rounded-lg transition"
            >
              {isLoggedIn ? t("dashboard") : t("signIn")}
            </Link>
          </div>

          {/* Mobile Menu Button */}
          <button
            className={`md:hidden p-2 transition-colors duration-300 ${isScrolled ? "text-gray-900" : "text-white"}`}
            onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
            aria-label={mobileMenuOpen ? t("closeMenu") : t("openMenu")}
            aria-expanded={mobileMenuOpen}
          >
            <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              {mobileMenuOpen ? (
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              ) : (
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
              )}
            </svg>
          </button>
        </div>

        {/* Mobile Menu */}
        {mobileMenuOpen && (
          <div className={`md:hidden py-4 border-t ${isScrolled ? "border-gray-200" : "border-white/10"}`}>
            <nav className="flex flex-col gap-2">
              {navLinks.map((link) => (
                <Link
                  key={link.name}
                  href={link.href}
                  className={`px-4 py-2 text-sm font-medium rounded-lg transition cursor-pointer ${
                    isScrolled
                      ? "text-gray-600 hover:text-gray-900 hover:bg-gray-100"
                      : "text-white/80 hover:text-white hover:bg-white/10"
                  }`}
                  onClick={(e) => {
                    handleLinkClick(e, link.href);
                    setMobileMenuOpen(false);
                  }}
                >
                  {link.name}
                </Link>
              ))}

              {/* Mobile Language Toggle */}
              <button
                onClick={toggleLanguage}
                aria-label={t("changeLanguage")}
                className={`mx-4 mt-2 flex items-center justify-center gap-2 px-4 py-2 text-sm rounded-lg transition cursor-pointer ${
                  isScrolled
                    ? "text-gray-600 hover:text-gray-900 bg-gray-100 hover:bg-gray-200"
                    : "text-white/80 hover:text-white bg-white/10 hover:bg-white/20"
                }`}
              >
                <FlagIcon locale={locale as "en" | "es"} />
                <span className="font-medium">{locale.toUpperCase()}</span>
              </button>

              <Link
                href={isLoggedIn ? getDashboardRoute() : "/login"}
                className="mx-4 mt-2 px-5 py-2 bg-[#3B9EC9] hover:bg-[#2D8AB5] text-white text-sm font-medium rounded-lg transition text-center"
                onClick={() => setMobileMenuOpen(false)}
              >
                {isLoggedIn ? t("dashboard") : t("signIn")}
              </Link>
            </nav>
          </div>
        )}
      </div>
    </header>
  );
}
