"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 { useProfile } from "@/api/user/user-profile/user-profile";
import { getUserDataCookie } from "@/lib/cookies";
import FlagIcon from "@/components/ui/FlagIcon";
import NotificationDropdown from "./NotificationDropdown";

interface DashboardHeaderProps {
  onEditProfile: () => void;
  onChangePassword: () => void;
  onSupport: () => void;
  onLogout: () => void;
  hasActiveSubscription: boolean;
}

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

  // Fetch user profile - will auto-update when cache is invalidated
  const { data: profileData } = useProfile();

  // Get user data from profile
  const userData = {
    name: profileData?.data?.user?.name || "",
    email: profileData?.data?.user?.email || "",
  };

  const [subscriptionType, setSubscriptionType] = useState<string | null>(null);
  useEffect(() => {
    setSubscriptionType(getUserDataCookie()?.subscription_type || null);
  }, []);

  const roleBadge = subscriptionType === "group"
    ? t("menu.roleBadgeManager")
    : subscriptionType === "individual"
    ? t("menu.roleBadgeTherapist")
    : null;

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

  const navLinks = [
    { name: t("nav.therapists"), href: "/practice-manager/dashboard", requiresSubscription: true },
    { name: t("nav.clients"), href: "/practice-manager/patients", requiresSubscription: true },
    { name: t("nav.documents"), href: "/practice-manager/documents", requiresSubscription: true },
    { name: t("nav.bibliography"), href: "/practice-manager/bibliography", requiresSubscription: false },
    { name: t("nav.subscription"), href: "/practice-manager/subscription", requiresSubscription: false },
  ];

  const handleNavClick = (e: React.MouseEvent<HTMLAnchorElement>, link: typeof navLinks[0]) => {
    // Silently block clicks on subscription-gated links — disabled style + tooltip
    // already signal to the user why navigation is unavailable.
    if (link.requiresSubscription && !hasActiveSubscription) {
      e.preventDefault();
    }
  };

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

  // Close dropdown when clicking outside
  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="/practice-manager/dashboard" className="flex items-center gap-2 cursor-pointer">
            <Image src={mbhsLogo} alt="MBHS" width={40} height={40} className="rounded-lg" />
            <span className="text-2xl font-extrabold text-gray-900">MBHS</span>
          </Link>

          {/* Center Navigation */}
          <nav className="hidden md:flex items-center gap-8">
            {navLinks.map((link) => {
              const isLocked = link.requiresSubscription && !hasActiveSubscription;
              return (
                <Link
                  key={link.name}
                  href={link.href}
                  onClick={(e) => handleNavClick(e, link)}
                  aria-disabled={isLocked}
                  title={isLocked ? t("nav.availableAfterPlan") : undefined}
                  className={`text-sm font-medium transition ${
                    isLocked
                      ? "text-gray-400 cursor-not-allowed"
                      : pathname === link.href
                      ? "text-[#3B9EC9] cursor-pointer"
                      : "text-gray-600 hover:text-gray-900 cursor-pointer"
                  }`}
                >
                  {link.name}
                </Link>
              );
            })}
          </nav>

          {/* Right Side */}
          <div className="flex items-center gap-2 md:gap-4">

            {/* Language Toggle */}
            <button
              onClick={toggleLanguage}
              className="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition cursor-pointer"
            >
              <FlagIcon locale={locale as "en" | "es"} />
              <span>{locale === "en" ? "EN" : "ES"}</span>
            </button>

            {/* Notification Bell */}
            <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"
              >
                {profileData?.data?.user?.profile_photo ? (
                  <div className="w-8 h-8 rounded-full overflow-hidden">
                    <Image
                      src={profileData.data.user.profile_photo}
                      alt="User"
                      width={32}
                      height={32}
                      className="w-full h-full object-cover"
                    />
                  </div>
                ) : (
                  <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
                    <svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                    </svg>
                  </div>
                )}
                <span className="hidden md:block text-sm font-medium text-gray-700">{userData?.name}</span>
                <svg
                  className={`hidden md:block 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">
                    {profileData?.data?.user?.profile_photo ? (
                      <div className="w-16 h-16 rounded-full overflow-hidden mb-3">
                        <img
                          src={profileData.data.user.profile_photo}
                          alt="User"
                          className="w-full h-full object-cover"
                        />
                      </div>
                    ) : (
                      <div className="w-16 h-16 rounded-full bg-gray-200 flex items-center justify-center mb-3">
                        <svg className="w-8 h-8 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                        </svg>
                      </div>
                    )}
                    <p className="text-sm font-semibold text-gray-900">{userData?.name}</p>
                    <p className="text-xs text-gray-500">{userData?.email}</p>
                    {roleBadge && (
                      <span className="mt-1.5 inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-[#3B9EC9]/10 text-[#3B9EC9]">
                        <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12c0 1.268-.63 2.39-1.593 3.068a3.745 3.745 0 01-1.043 3.296 3.745 3.745 0 01-3.296 1.043A3.745 3.745 0 0112 21c-1.268 0-2.39-.63-3.068-1.593a3.746 3.746 0 01-3.296-1.043 3.745 3.745 0 01-1.043-3.296A3.745 3.745 0 013 12c0-1.268.63-2.39 1.593-3.068a3.745 3.745 0 011.043-3.296 3.746 3.746 0 013.296-1.043A3.746 3.746 0 0112 3c1.268 0 2.39.63 3.068 1.593a3.746 3.746 0 013.296 1.043 3.745 3.745 0 011.043 3.296A3.745 3.745 0 0121 12z" />
                        </svg>
                        {roleBadge}
                      </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("menu.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("menu.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("menu.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("menu.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) => {
                const isLocked = link.requiresSubscription && !hasActiveSubscription;
                return (
                  <Link
                    key={link.name}
                    href={link.href}
                    onClick={(e) => {
                      handleNavClick(e, link);
                      if (!isLocked) setMobileMenuOpen(false);
                    }}
                    aria-disabled={isLocked}
                    title={isLocked ? t("nav.availableAfterPlan") : undefined}
                    className={`px-4 py-2.5 text-sm font-medium rounded-lg transition ${
                      isLocked
                        ? "text-gray-400 cursor-not-allowed"
                        : pathname === link.href
                        ? "text-[#3B9EC9] bg-[#3B9EC9]/5 cursor-pointer"
                        : "text-gray-600 hover:text-gray-900 hover:bg-gray-50 cursor-pointer"
                    }`}
                  >
                    {link.name}
                  </Link>
                );
              })}
              <div className="mt-2 pt-2 border-t border-gray-100 flex items-center gap-3 px-4">
                <button
                  onClick={toggleLanguage}
                  className="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition cursor-pointer"
                >
                  <span>{locale === "en" ? "🇺🇸" : "🇪🇸"}</span>
                  <span>{locale === "en" ? "EN" : "ES"}</span>
                </button>
                <button
                  onClick={() => { setMobileMenuOpen(false); onLogout(); }}
                  className="text-sm text-red-500 hover:text-red-700 transition cursor-pointer ml-auto"
                >
                  {t("menu.logout")}
                </button>
              </div>
            </nav>
          </div>
        )}
      </div>
    </header>
  );
}
