"use client";

import Image from "next/image";
import mbhsLogo from "@/public/images/mbhs-logo.png";
import { Link, useRouter, usePathname } from "@/i18n/navigation";
import { useState, useRef, useEffect } from "react";
import { useTranslations, useLocale } from "next-intl";
import { useSearchParams } from "next/navigation";
import NotificationDropdown from "./NotificationDropdown";
import FlagIcon from "@/components/ui/FlagIcon";

interface UserData {
  uuid: string;
  name: string;
  email: string;
  isd_code?: string | null;
  mobile?: string | null;
  locale?: string;
  profile_photo?: string | null;
  role?: {
    uuid: string | null;
    name: string | null;
  } | null;
}

interface IndividualHeaderProps {
  user?: UserData;
  onEditProfile: () => void;
  onChangePassword: () => void;
  onSupport: () => void;
  onLogout: () => void;
}

export default function IndividualHeader({
  user,
  onEditProfile,
  onChangePassword,
  onSupport,
  onLogout,
}: IndividualHeaderProps) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [userDropdownOpen, setUserDropdownOpen] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const userDropdownRef = useRef<HTMLDivElement>(null);
  const t = useTranslations("individual.header");
  const locale = useLocale();
  const router = useRouter();

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

  const navLinks = [
    { name: t("dashboard"), href: "/individual" },
    { name: t("bibliography"), href: "/bibliography" },
    { name: t("subscription"), href: "/individual/subscription" },
  ];

  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 });
  };

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        userDropdownRef.current &&
        !userDropdownRef.current.contains(event.target as Node)
      ) {
        setUserDropdownOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  return (
    <header className="fixed top-0 left-0 right-0 z-50 bg-white border-b border-gray-100">
      <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="/individual" className="flex items-center gap-2 cursor-pointer">
            <Image src={mbhsLogo} alt="MBHS" width={40} height={40} className="rounded-lg" />
            <span className="text-xl font-bold text-gray-900">MBHS</span>
          </Link>

          {/* Center Navigation */}
          <nav className="hidden md:flex items-center gap-8">
            {navLinks.map((link) => (
              <Link
                key={link.name}
                href={link.href}
                className={`text-sm font-medium transition relative cursor-pointer ${
                  pathname === link.href
                    ? "text-[#3B9EC9]"
                    : "text-gray-600 hover:text-gray-900"
                }`}
              >
                {link.name}
                {pathname === link.href && (
                  <span className="absolute -bottom-[21px] left-0 right-0 h-0.5 bg-[#3B9EC9]"></span>
                )}
              </Link>
            ))}
          </nav>

          {/* Right Side */}
          <div className="flex items-center gap-4">
            {/* Language Toggle */}
            <button
              onClick={toggleLanguage}
              className="flex items-center gap-1.5 px-2 py-1.5 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-50 rounded-lg transition cursor-pointer"
            >
              <FlagIcon locale={locale as "en" | "es"} />
              <span className="font-medium">{locale.toUpperCase()}</span>
            </button>

            {/* Notifications */}
            <NotificationDropdown />

            {/* Mobile Hamburger */}
            <button
              className="md:hidden p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-50 rounded-lg transition cursor-pointer"
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
            >
              <svg className="w-5 h-5" 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>

            {/* User Dropdown */}
            <div className="relative" ref={userDropdownRef}>
              <button
                onClick={() => setUserDropdownOpen(!userDropdownOpen)}
                className="flex items-center gap-2 px-2 py-1.5 hover:bg-gray-50 rounded-lg transition cursor-pointer"
              >
                {user?.profile_photo ? (
                  <img
                    src={user.profile_photo}
                    alt="User"
                    width={32}
                    height={32}
                    className="w-8 h-8 rounded-full object-cover"
                  />
                ) : (
                  <div className="w-8 h-8 rounded-full bg-[#3B9EC9] flex items-center justify-center text-white font-medium text-sm">
                    {user?.name?.charAt(0)?.toUpperCase() || "U"}
                  </div>
                )}
                <span className="hidden sm:block text-sm font-medium text-gray-700">
                  {user?.name || "User"}
                </span>
                <svg
                  className={`w-4 h-4 text-gray-500 transition-transform ${
                    userDropdownOpen ? "rotate-180" : ""
                  }`}
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M19 9l-7 7-7-7"
                  />
                </svg>
              </button>

              {/* Dropdown Menu */}
              {userDropdownOpen && (
                <div className="absolute right-0 mt-2 w-56 bg-white rounded-2xl shadow-xl border border-gray-100 py-4 z-50">
                  {/* Profile Section */}
                  <div className="flex flex-col items-center px-4 pb-4">
                    {user?.profile_photo ? (
                      <img
                        src={user.profile_photo}
                        alt="User"
                        width={64}
                        height={64}
                        className="w-16 h-16 rounded-full object-cover mb-3"
                      />
                    ) : (
                      <div className="w-16 h-16 rounded-full bg-[#3B9EC9] flex items-center justify-center text-white font-bold text-2xl mb-3">
                        {user?.name?.charAt(0)?.toUpperCase() || "U"}
                      </div>
                    )}
                    <p className="text-sm font-semibold text-gray-900">{user?.name || "User"}</p>
                    <p className="text-xs text-gray-500">{user?.email || ""}</p>
                    {user?.role?.name && (
                      <span className="mt-1.5 inline-block px-3 py-0.5 text-xs font-medium text-[#3B9EC9] bg-[#3B9EC9]/10 rounded-full">
                        {user.role.name}
                      </span>
                    )}
                  </div>

                  {/* Menu Items */}
                  <div className="px-3 space-y-1">
                    <button
                      onClick={() => {
                        setUserDropdownOpen(false);
                        onEditProfile();
                      }}
                      className="w-full flex items-center gap-3 px-3 py-2.5 text-sm text-gray-700 hover:bg-gray-50 rounded-xl border border-gray-100 transition cursor-pointer"
                    >
                      <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                      </svg>
                      {t("manageProfile")}
                    </button>
                    <button
                      onClick={() => {
                        setUserDropdownOpen(false);
                        onChangePassword();
                      }}
                      className="w-full flex items-center gap-3 px-3 py-2.5 text-sm text-gray-700 hover:bg-gray-50 rounded-xl border border-gray-100 transition cursor-pointer"
                    >
                      <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                      </svg>
                      {t("changePassword")}
                    </button>
                    <button
                      onClick={() => {
                        setUserDropdownOpen(false);
                        onSupport();
                      }}
                      className="w-full flex items-center gap-3 px-3 py-2.5 text-sm text-gray-700 hover:bg-gray-50 rounded-xl border border-gray-100 transition cursor-pointer"
                    >
                      <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z" />
                      </svg>
                      {t("support")}
                    </button>
                    <button
                      onClick={() => {
                        setUserDropdownOpen(false);
                        onLogout();
                      }}
                      className="w-full flex items-center gap-3 px-3 py-2.5 text-sm text-gray-700 hover:bg-gray-50 rounded-xl border border-gray-100 transition cursor-pointer"
                    >
                      <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                      </svg>
                      {t("logout")}
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
        {/* Mobile Menu */}
        {mobileMenuOpen && (
          <div className="md:hidden border-t border-gray-100 py-3">
            <nav className="flex flex-col gap-1">
              {navLinks.map((link) => (
                <Link
                  key={link.name}
                  href={link.href}
                  onClick={() => setMobileMenuOpen(false)}
                  className={`px-4 py-2.5 text-sm font-medium rounded-lg transition cursor-pointer ${
                    pathname === link.href
                      ? "text-[#3B9EC9] bg-[#3B9EC9]/5"
                      : "text-gray-600 hover:text-gray-900 hover:bg-gray-50"
                  }`}
                >
                  {link.name}
                </Link>
              ))}
            </nav>
          </div>
        )}
      </div>
    </header>
  );
}
