"use client";

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


interface AdminHeaderProps {
  onEditProfile: () => void;
  onChangePassword: () => void;
  onLogout: () => void;
}

export default function AdminHeader({
  onEditProfile,
  onChangePassword,
  onLogout,
}: AdminHeaderProps) {
  const t = useTranslations();
  const locale = useLocale();
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [userDropdownOpen, setUserDropdownOpen] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [userData, setUserData] = useState<UserData | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Get profile data from API (includes profile_photo)
  const { data: profileData } = useProfileControllerGetProfileV1();
  const profilePhoto = profileData?.data?.profile?.profile_photo;
  const profileName = profileData?.data?.profile?.name;
  const profileEmail = profileData?.data?.profile?.email;

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

  // Get user data from cookie as fallback
  useEffect(() => {
    const data = getUserDataCookie();
    setUserData(data);
  }, []);

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

  const navLinks = [
    { href: "/admin", label: t("admin.nav.dashboard"), key: "dashboard" },
    { href: "/admin/subscription", label: t("admin.nav.subscription"), key: "subscription" },
    { href: "/admin/users", label: t("admin.nav.users"), key: "users" },
    { href: "/admin/documents", label: t("admin.nav.documents"), key: "documents" },
    { href: "/admin/bibliography", label: t("admin.nav.bibliography"), key: "bibliography" },
    { href: "/admin/lead", label: t("admin.nav.lead"), key: "lead" },
    { href: "/admin/support", label: t("admin.nav.support"), key: "support" },
  ];

  const isActive = (href: string) => {
    if (href === "/admin") {
      return pathname === "/admin" || pathname === "/admin/dashboard";
    }
    return pathname === href || pathname.startsWith(href + "/");
  };

  const getInitials = (name: string) => {
    return name
      .split(' ')
      .map(n => n.charAt(0))
      .join('')
      .toUpperCase()
      .slice(0, 2);
  };

  return (
    <header className="bg-white border-b border-gray-100 sticky top-0 z-40">
      <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="/admin" 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>

          {/* Navigation */}
          <nav className="hidden md:flex items-center gap-8">
            {navLinks.map((link) => (
              <Link
                key={link.key}
                href={link.href}
                className={`text-sm font-medium cursor-pointer ${
                  isActive(link.href)
                    ? "text-[#3B9EC9] border-b-2 border-[#3B9EC9] pb-1"
                    : "text-gray-600 hover:text-gray-900"
                }`}
              >
                {link.label}
              </Link>
            ))}
          </nav>

          {/* Hamburger button - mobile only */}
          <button
            className="md:hidden p-2 text-gray-700 hover:bg-gray-100 rounded-lg transition"
            onClick={() => setMobileMenuOpen(!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>

          {/* Right side */}
          <div className="hidden md:flex items-center gap-4">
            {/* Language Toggle Button */}
            <button
              onClick={() => {
                const newLocale = locale === "en" ? "es" : "en";
                const queryString = searchParams.toString();
                const pathnameWithQuery = queryString ? `${pathname}?${queryString}` : pathname;
                router.replace(pathnameWithQuery, { locale: newLocale });
              }}
              className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 hover:bg-gray-200 rounded-full text-sm font-medium text-gray-700 transition cursor-pointer"
            >
              <FlagIcon locale={locale as "en" | "es"} />
              <span>{locale === "en" ? "EN" : "ES"}</span>
            </button>

            {/* API Logs */}
            <Link
              href="/admin/api-logs"
              title={t("admin.nav.apiLogs")}
              className={`p-1.5 rounded-lg transition cursor-pointer ${
                isActive("/admin/api-logs")
                  ? "text-[#3B9EC9] bg-[#3B9EC9]/10"
                  : "text-gray-500 hover:text-gray-700 hover:bg-gray-100"
              }`}
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={`${process.env.NEXT_PUBLIC_BASE_PATH || ''}/images/icons/${isActive("/admin/api-logs") ? "logs-active" : "logs-gray"}.svg`}
                alt="API Logs"
                width={22}
                height={22}
                className="w-[22px] h-[22px]"
              />
            </Link>

            {/* Audit Logs */}
            <Link
              href="/admin/audit-logs"
              title={t("admin.nav.auditLogs")}
              className={`p-1.5 rounded-lg transition cursor-pointer ${
                isActive("/admin/audit-logs")
                  ? "text-[#3B9EC9] bg-[#3B9EC9]/10"
                  : "text-gray-500 hover:text-gray-700 hover:bg-gray-100"
              }`}
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={`${process.env.NEXT_PUBLIC_BASE_PATH || ''}/images/icons/${isActive("/admin/audit-logs") ? "audit-active" : "audit-gray"}.svg`}
                alt="Audit Logs"
                width={22}
                height={22}
                className="w-[22px] h-[22px]"
              />
            </Link>

            {/* Notification Dropdown */}
            <NotificationDropdown />

            {/* User Dropdown */}
            <div className="relative" ref={dropdownRef}>
              <button
                onClick={() => setUserDropdownOpen(!userDropdownOpen)}
                className="flex items-center gap-2 hover:bg-gray-50 rounded-lg px-2 py-1 transition cursor-pointer"
              >
                {profilePhoto ? (
                  <div className="w-8 h-8 rounded-full overflow-hidden relative">
                    <Image
                      src={profilePhoto}
                      alt="Profile"
                      fill
                      className="object-cover"
                    />
                  </div>
                ) : (
                  <div className="w-8 h-8 rounded-full bg-[#3B9EC9] flex items-center justify-center text-white text-sm font-medium">
                    {(profileName || userData?.name) ? getInitials(profileName || userData?.name || '') : 'A'}
                  </div>
                )}
                <span className="text-sm font-medium text-gray-700">{profileName || userData?.name || 'Admin'}</span>
                <svg className={`w-4 h-4 text-gray-400 transition ${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>

              {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">
                    {profilePhoto ? (
                      <div className="w-16 h-16 rounded-full overflow-hidden relative mb-3">
                        <Image
                          src={profilePhoto}
                          alt="Profile"
                          fill
                          className="object-cover"
                        />
                      </div>
                    ) : (
                      <div className="w-16 h-16 rounded-full bg-[#3B9EC9] flex items-center justify-center text-white text-xl font-medium mb-3">
                        {(profileName || userData?.name) ? getInitials(profileName || userData?.name || '') : 'A'}
                      </div>
                    )}
                    <p className="text-sm font-semibold text-gray-900">{profileName || userData?.name || 'Admin'}</p>
                    <p className="text-xs text-gray-500">{profileEmail || userData?.email || ''}</p>
                  </div>

                  {/* Menu Items */}
                  <div className="px-3 space-y-1">
                    <button
                      onClick={() => {
                        onEditProfile();
                        setUserDropdownOpen(false);
                      }}
                      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("admin.common.manageProfile")}
                    </button>
                    <button
                      onClick={() => {
                        onChangePassword();
                        setUserDropdownOpen(false);
                      }}
                      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("admin.common.changePassword")}
                    </button>
                    <button
                      onClick={() => {
                        onLogout();
                        setUserDropdownOpen(false);
                      }}
                      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("admin.common.logout")}
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Mobile Nav Menu */}
      {mobileMenuOpen && (
        <div className="md:hidden border-t border-gray-100 bg-white px-4 py-3">
          <nav className="flex flex-col gap-1">
            {navLinks.map((link) => (
              <Link
                key={link.key}
                href={link.href}
                onClick={() => setMobileMenuOpen(false)}
                className={`px-4 py-2.5 text-sm font-medium rounded-lg transition ${
                  isActive(link.href)
                    ? "bg-[#3B9EC9]/10 text-[#3B9EC9]"
                    : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"
                }`}
              >
                {link.label}
              </Link>
            ))}
            {/* Language & profile actions on mobile */}
            <div className="mt-2 pt-2 border-t border-gray-100 flex items-center gap-3 px-4">
              <button
                onClick={() => {
                  const newLocale = locale === "en" ? "es" : "en";
                  const queryString = searchParams.toString();
                  const pathnameWithQuery = queryString ? `${pathname}?${queryString}` : pathname;
                  router.replace(pathnameWithQuery, { locale: newLocale });
                  setMobileMenuOpen(false);
                }}
                className="flex items-center gap-1.5 px-3 py-2 bg-gray-100 hover:bg-gray-200 rounded-full text-sm font-medium text-gray-700 transition cursor-pointer"
              >
                <FlagIcon locale={locale as "en" | "es"} />
                <span>{locale === "en" ? "EN" : "ES"}</span>
              </button>
              <button
                onClick={() => {
                  onEditProfile();
                  setMobileMenuOpen(false);
                }}
                className="flex-1 px-3 py-2 text-sm font-medium text-gray-700 bg-gray-50 hover:bg-gray-100 rounded-lg transition text-center"
              >
                {t("admin.common.manageProfile")}
              </button>
              <button
                onClick={() => {
                  onLogout();
                  setMobileMenuOpen(false);
                }}
                className="px-3 py-2 text-sm font-medium text-red-600 bg-red-50 hover:bg-red-100 rounded-lg transition"
              >
                {t("admin.common.logout")}
              </button>
            </div>
          </nav>
        </div>
      )}
    </header>
  );
}
