"use client";

import {
  Bell,
  LogOut,
  Menu,
  Lock,
  ChevronDown,
  LayoutGrid,
  FileText,
  Users as UsersIcon,
  MessageSquare,
  Calendar,
  BarChart3,
  Settings,
  Building2,
  UserCog,
  DollarSign,
  Shield,
  Plug,
  Headphones,
  Activity,
} from "lucide-react";
import { useState, useRef, useEffect } from "react";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
import BrandLogo from "@/components/BrandLogo";

interface StaffHeaderProps {
  user: {
    name: string;
    email: string;
    role: string;
  };
}

export default function StaffHeader({ user }: StaffHeaderProps) {
  const router = useRouter();
  const pathname = usePathname();
  const [showProfileMenu, setShowProfileMenu] = useState(false);
  const [showMobileMenu, setShowMobileMenu] = useState(false);
  const [showChangePassword, setShowChangePassword] = useState(false);
  const [showMoreMenu, setShowMoreMenu] = useState(false);
  const moreMenuRef = useRef<HTMLDivElement>(null);

  const handleLogout = async () => {
    await fetch("/api/staff/auth/logout", { method: "POST" });
    router.push("/en/clerk-login?redirect_url=%2Fstaff%2Fdashboard");
  };

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

  const navItems = [
    {
      name: "Overview",
      href: "/staff/dashboard",
      roles: ["STAFF", "ADMIN", "SUPER_ADMIN"],
      icon: LayoutGrid,
    },
    {
      name: "Demos",
      href: "/staff/dashboard/demos",
      roles: ["STAFF", "ADMIN", "SUPER_ADMIN"],
      icon: Calendar,
    },
    {
      name: "Contacts",
      href: "/staff/dashboard/contacts",
      roles: ["STAFF", "ADMIN", "SUPER_ADMIN"],
      icon: MessageSquare,
    },
    {
      name: "Users",
      href: "/staff/dashboard/users",
      roles: ["STAFF", "ADMIN", "SUPER_ADMIN"],
      icon: UsersIcon,
    },
    {
      name: "Organizations",
      href: "/staff/dashboard/organizations",
      roles: ["ADMIN", "SUPER_ADMIN"],
      icon: Building2,
    },
    {
      name: "Support",
      href: "/staff/dashboard/support",
      roles: ["STAFF", "ADMIN", "SUPER_ADMIN"],
      icon: Headphones,
    },
    {
      name: "Refunds",
      href: "/staff/dashboard/refunds",
      roles: ["ADMIN", "SUPER_ADMIN"],
      icon: DollarSign,
    },
    {
      name: "Security",
      href: "/staff/dashboard/security",
      roles: ["ADMIN", "SUPER_ADMIN"],
      icon: Shield,
    },
    {
      name: "Integrations",
      href: "/staff/dashboard/integrations",
      roles: ["ADMIN", "SUPER_ADMIN"],
      icon: Plug,
    },
    {
      name: "Site Experience",
      href: "/staff/dashboard/site-experience",
      roles: ["STAFF", "ADMIN", "SUPER_ADMIN"],
      icon: Settings,
    },
    {
      name: "Blog",
      href: "/staff/dashboard/blog",
      roles: ["ADMIN", "SUPER_ADMIN"],
      icon: FileText,
    },
    {
      name: "Careers",
      href: "/staff/dashboard/careers",
      roles: ["STAFF", "ADMIN", "SUPER_ADMIN"],
      icon: UsersIcon,
    },
    {
      name: "System Messages",
      href: "/staff/dashboard/system-messages",
      roles: ["ADMIN", "SUPER_ADMIN"],
      icon: MessageSquare,
    },
    {
      name: "Analytics",
      href: "/staff/dashboard/analytics",
      roles: ["STAFF", "ADMIN", "SUPER_ADMIN"],
      icon: BarChart3,
    },
    {
      name: "Logging",
      href: "/staff/dashboard/logging",
      roles: ["ADMIN", "SUPER_ADMIN"],
      icon: Activity,
    },
    {
      name: "Staff",
      href: "/staff/dashboard/staff",
      roles: ["SUPER_ADMIN"],
      icon: UserCog,
    },
  ];

  const filteredNavItems = navItems.filter((item) =>
    item.roles.includes(user.role),
  );

  // Split into primary (first 5) and secondary (rest) for overflow menu
  const primaryNavItems = filteredNavItems.slice(0, 5);
  const secondaryNavItems = filteredNavItems.slice(5);
  const isSecondaryActive = secondaryNavItems.some(
    (item) => pathname === item.href,
  );

  return (
    <header className="fixed top-0 left-0 right-0 bg-white/95 backdrop-blur-md border-b border-gray-200/80 z-50">
      <div className="h-16 px-4 lg:px-6 flex items-center justify-between max-w-[1800px] mx-auto">
        {/* Left: Mobile Menu Button + Logo */}
        <div className="flex items-center gap-3">
          {/* Mobile Menu Button - LEFT SIDE */}
          <button
            onClick={() => setShowMobileMenu(!showMobileMenu)}
            className="xl:hidden p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition"
            aria-label="Menu"
          >
            <Menu className="w-5 h-5" />
          </button>

          <Link href="/staff/dashboard" className="flex items-center gap-3">
            <BrandLogo size="sm" />
            <span className="hidden sm:inline-flex items-center px-2.5 py-1 bg-gradient-to-r from-brand-green/10 to-emerald-50 text-brand-green text-[11px] font-bold rounded-md uppercase tracking-wide border border-brand-green/20">
              Staff
            </span>
          </Link>
        </div>

        {/* Center: Navigation */}
        <nav className="hidden xl:flex items-center gap-1 flex-1 justify-center">
          {primaryNavItems.map((item) => {
            const isActive = pathname === item.href;
            const Icon = item.icon;
            return (
              <Link
                key={item.href}
                href={item.href}
                className={`group flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                  isActive
                    ? "bg-brand-green text-white shadow-sm shadow-brand-green/25"
                    : "text-gray-600 hover:bg-gray-100 hover:text-brand-ink"
                }`}
              >
                <Icon
                  className={`w-4 h-4 ${isActive ? "text-white" : "text-gray-400 group-hover:text-gray-600"}`}
                />
                {item.name}
              </Link>
            );
          })}

          {/* More dropdown for secondary items */}
          {secondaryNavItems.length > 0 && (
            <div className="relative" ref={moreMenuRef}>
              <button
                onClick={() => setShowMoreMenu(!showMoreMenu)}
                className={`flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                  isSecondaryActive
                    ? "bg-brand-green text-white shadow-sm shadow-brand-green/25"
                    : "text-gray-600 hover:bg-gray-100 hover:text-brand-ink"
                }`}
              >
                More
                <ChevronDown
                  className={`w-4 h-4 transition-transform ${showMoreMenu ? "rotate-180" : ""}`}
                />
              </button>

              {showMoreMenu && (
                <div className="absolute top-full left-0 mt-2 w-56 bg-white rounded-xl shadow-lg border border-gray-200 py-2 z-50">
                  {secondaryNavItems.map((item) => {
                    const isActive = pathname === item.href;
                    const Icon = item.icon;
                    return (
                      <Link
                        key={item.href}
                        href={item.href}
                        onClick={() => setShowMoreMenu(false)}
                        className={`flex items-center gap-3 px-4 py-2.5 text-sm transition-colors ${
                          isActive
                            ? "bg-brand-green/10 text-brand-green font-semibold"
                            : "text-gray-700 hover:bg-gray-50"
                        }`}
                      >
                        <Icon
                          className={`w-4 h-4 ${isActive ? "text-brand-green" : "text-gray-400"}`}
                        />
                        {item.name}
                      </Link>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </nav>

        {/* Right: Notifications & User Profile */}
        <div className="flex items-center gap-2">
          {/* Notifications */}
          <button
            className="relative p-2 text-gray-500 hover:text-brand-ink hover:bg-gray-100 rounded-lg transition"
            aria-label="Notifications"
          >
            <Bell className="w-5 h-5" />
            <span className="absolute top-1.5 right-1.5 w-2 h-2 bg-red-500 rounded-full ring-2 ring-white"></span>
          </button>

          {/* Divider */}
          <div className="hidden sm:block h-8 w-px bg-gray-200 mx-1"></div>

          {/* User Profile */}
          <div className="relative">
            <button
              onClick={() => setShowProfileMenu(!showProfileMenu)}
              className="flex items-center gap-2.5 pl-2 pr-3 py-1.5 text-gray-700 hover:bg-gray-100 rounded-xl transition"
            >
              <div className="w-8 h-8 bg-gradient-to-br from-brand-green to-emerald-600 rounded-full flex items-center justify-center shadow-sm">
                <span className="text-sm font-bold text-white">
                  {user.name.charAt(0).toUpperCase()}
                </span>
              </div>
              <div className="hidden lg:block text-left">
                <p className="text-sm font-semibold text-brand-ink leading-tight">
                  {user.name}
                </p>
                <p className="text-[11px] text-gray-500 capitalize">
                  {user.role.toLowerCase().replace("_", " ")}
                </p>
              </div>
              <ChevronDown className="hidden lg:block w-4 h-4 text-gray-400" />
            </button>

            {/* Profile Dropdown */}
            {showProfileMenu && (
              <>
                <div
                  className="fixed inset-0 z-40"
                  onClick={() => setShowProfileMenu(false)}
                ></div>
                <div className="absolute right-0 mt-2 w-64 bg-white rounded-xl shadow-xl border border-gray-200 z-50 overflow-hidden">
                  {/* User Info */}
                  <div className="p-4 bg-gradient-to-br from-gray-50 to-white border-b border-gray-100">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-gradient-to-br from-brand-green to-emerald-600 rounded-full flex items-center justify-center shadow">
                        <span className="text-base font-bold text-white">
                          {user.name.charAt(0).toUpperCase()}
                        </span>
                      </div>
                      <div>
                        <p className="text-sm font-semibold text-brand-ink">
                          {user.name}
                        </p>
                        <p className="text-xs text-gray-500 truncate max-w-[160px]">
                          {user.email}
                        </p>
                      </div>
                    </div>
                    <span className="inline-flex items-center mt-3 px-2.5 py-1 bg-brand-green/10 text-brand-green text-[11px] font-bold rounded-md uppercase tracking-wide">
                      {user.role.replace("_", " ")}
                    </span>
                  </div>

                  {/* Menu Items */}
                  <div className="p-2">
                    <button
                      onClick={() => {
                        setShowProfileMenu(false);
                        setShowChangePassword(true);
                      }}
                      className="w-full flex items-center gap-3 px-3 py-2.5 text-sm text-gray-700 hover:bg-gray-100 rounded-lg transition"
                    >
                      <Lock className="w-4 h-4 text-gray-400" />
                      Change Password
                    </button>
                    <button
                      onClick={handleLogout}
                      className="w-full flex items-center gap-3 px-3 py-2.5 text-sm text-red-600 hover:bg-red-50 rounded-lg transition"
                    >
                      <LogOut className="w-4 h-4" />
                      Sign Out
                    </button>
                  </div>
                </div>
              </>
            )}
          </div>
        </div>
      </div>

      {/* Mobile Navigation Dropdown */}
      {showMobileMenu && (
        <>
          <div
            className="fixed inset-0 bg-black/30 backdrop-blur-sm z-40 xl:hidden"
            onClick={() => setShowMobileMenu(false)}
          />
          <div className="xl:hidden absolute top-16 left-0 right-0 bg-white border-b border-gray-200 shadow-xl z-50 max-h-[calc(100vh-4rem)] overflow-y-auto">
            <nav className="p-3">
              <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
                {filteredNavItems.map((item) => {
                  const isActive = pathname === item.href;
                  const Icon = item.icon;
                  return (
                    <Link
                      key={item.href}
                      href={item.href}
                      onClick={() => setShowMobileMenu(false)}
                      className={`flex flex-col items-center gap-2 p-4 rounded-xl text-center transition ${
                        isActive
                          ? "bg-brand-green text-white shadow-md"
                          : "text-gray-700 hover:bg-gray-100 border border-gray-100"
                      }`}
                    >
                      <Icon
                        className={`w-5 h-5 ${isActive ? "text-white" : "text-gray-400"}`}
                      />
                      <span className="text-xs font-semibold">{item.name}</span>
                    </Link>
                  );
                })}
              </div>
              <div className="mt-4 pt-4 border-t border-gray-100">
                <div className="flex items-center justify-between px-2">
                  <span className="text-xs text-gray-500">Signed in as</span>
                  <span className="text-xs font-semibold text-brand-green uppercase">
                    {user.role.replace("_", " ")}
                  </span>
                </div>
              </div>
            </nav>
          </div>
        </>
      )}

      {/* Change Password Modal */}
      {showChangePassword && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden">
            {/* Modal Header */}
            <div className="px-6 py-5 bg-gradient-to-r from-gray-50 to-white border-b border-gray-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-brand-green/10 rounded-xl flex items-center justify-center">
                  <Lock className="w-5 h-5 text-brand-green" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-brand-ink">
                    Change Password
                  </h3>
                  <p className="text-sm text-gray-500">
                    Update your account password
                  </p>
                </div>
              </div>
            </div>

            {/* Modal Body */}
            <form
              onSubmit={async (e) => {
                e.preventDefault();
                const formData = new FormData(e.currentTarget);
                const currentPassword = formData.get(
                  "currentPassword",
                ) as string;
                const newPassword = formData.get("newPassword") as string;
                const confirmPassword = formData.get(
                  "confirmPassword",
                ) as string;

                if (newPassword !== confirmPassword) {
                  alert("Passwords do not match");
                  return;
                }

                try {
                  const response = await fetch(
                    "/api/staff/auth/change-password",
                    {
                      method: "POST",
                      headers: { "Content-Type": "application/json" },
                      body: JSON.stringify({ currentPassword, newPassword }),
                    },
                  );

                  const data = await response.json();

                  if (response.ok) {
                    alert("Password updated successfully!");
                    setShowChangePassword(false);
                  } else {
                    alert(data.error || "Failed to update password");
                  }
                } catch {
                  alert("An error occurred. Please try again.");
                }
              }}
              className="p-6"
            >
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1.5">
                    Current Password
                  </label>
                  <input
                    type="password"
                    name="currentPassword"
                    required
                    className="w-full px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green transition-colors"
                    placeholder="Enter current password"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1.5">
                    New Password
                  </label>
                  <input
                    type="password"
                    name="newPassword"
                    required
                    minLength={12}
                    className="w-full px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green transition-colors"
                    placeholder="Min 12 characters"
                  />
                  <p className="text-xs text-gray-500 mt-1.5">
                    Must include uppercase, lowercase, and numbers
                  </p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1.5">
                    Confirm New Password
                  </label>
                  <input
                    type="password"
                    name="confirmPassword"
                    required
                    minLength={12}
                    className="w-full px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green transition-colors"
                    placeholder="Re-enter new password"
                  />
                </div>
              </div>
              <div className="flex gap-3 mt-6">
                <button
                  type="button"
                  onClick={() => setShowChangePassword(false)}
                  className="flex-1 px-4 py-2.5 border border-gray-300 text-gray-700 font-medium rounded-xl hover:bg-gray-50 transition"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 px-4 py-2.5 bg-brand-green text-white font-medium rounded-xl hover:bg-brand-greenHover shadow-sm transition"
                >
                  Update Password
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </header>
  );
}
