"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { usePathname } from "next/navigation";
import { useAppSelector } from "../../hooks/useAppRedux";
import { useModal } from "../../lib/modal-system/ModalContext";
import { Role } from "../../lib/auth/helper";
import { UserImage } from "../ui/CustomImage";
import CustomLink from "../ui/CustomLink";

type NavItem = [href: string, label: string];

const nav: NavItem[] = [
  ["/", "Home"],
  ["/for-companies", "For Companies"],
  ["/detect-image", "Image Detector"],
  ["/about", "About Us"],
];

interface HeaderProps {
  onSignIn?: () => void;
}

interface SignInButtonProps {
  className?: string;
  onClick?: () => void;
}

export default function Header({ onSignIn }: HeaderProps) {
  const [scrolled, setScrolled] = useState<boolean>(false);
  const [menuOpen, setMenuOpen] = useState<boolean>(false);
  const [isMounted, setIsMounted] = useState<boolean>(false);
  const pathname = usePathname();
  const { openModal } = useModal();

  const user = useAppSelector((state) => state.user.user);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  const links =
    isMounted && user?.role?.includes(Role.ADMIN) ? [["/admin", "Admin"]] : nav;
  useEffect(() => {
    const handleScroll = (): void => {
      setScrolled(window.scrollY > 1);
    };

    handleScroll();
    window.addEventListener("scroll", handleScroll);

    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  const handleSignIn = (): void => {
    setMenuOpen(false);
    onSignIn?.();
  };

  return (
    <header
      className={`fixed left-0 top-0 z-50 w-full transition-all duration-500 ${
        scrolled
          ? "bg-white/70 py-3 header-shadow backdrop-blur-xl md:py-2"
          : "bg-transparent pt-4 md:pt-5"
      }`}
    >
      <div className="container-k">
        <div
          className={`relative flex items-center justify-between transition-all duration-500 ${
            scrolled
              ? "rounded-none border-transparent bg-transparent px-0 shadow-none"
              : "header-shadow rounded-full border-2 border-white/55 bg-white/10 px-3 xl:px-10 py-3 backdrop-blur-3xl"
          }`}
        >
          <CustomLink
            href="/"
            onClick={() => setMenuOpen(false)}
            className="flex items-center gap-2"
          >
            <Image
              src="/images/logo.svg"
              alt="KleboAI"
              width={83}
              height={67}
              priority
              className="h-auto w-16 sm:w-20"
            />
          </CustomLink>

          <nav className="hidden items-center gap-6 xl:gap-10 md:flex">
            {nav.map(([href, label]) => {
              const isActive =
                href === "/" ? pathname === "/" : pathname.startsWith(href);

              return (
                <CustomLink
                  key={href}
                  href={href}
                  className={`group relative font-heading text-base font-medium transition-all duration-300 hover:-translate-y-0.5 ${
                    isActive ? "text-gradient" : "text-text hover:text-gradient"
                  }`}
                >
                  {label}
                </CustomLink>
              );
            })}
          </nav>

          <div className="flex gap-3 items-center">
            {isMounted ? (
              user ? (
                <div className="flex items-center gap-2 xl:gap-5">
                  {user?.role?.includes(Role.USER) && (
                    <div className="hidden md:block bg-transparent p-0 shadow-none md:gradient1 md:p-px md:shadow-button rounded-full">
                      <div className="flex items-center p-0 md:py-2 md:px-3 xl:px-5 gap-2 xl:gap-3 bg-transparent md:bg-white rounded-full">
                        <Image
                          src="/images/credits-icon.svg"
                          alt="Credits"
                          width={28}
                          height={28}
                          priority
                          className="h-5! w-5! md:w-7! md:h-7!"
                        />
                        <div>
                          <p className="font-heading text-xs xl:text-sm font-medium leading-none text-link">
                            {user?.balance || 0} left!
                          </p>

                          <CustomLink
                            href={
                              user?.isVerified ? "/dashboard/packages" : "#"
                            }
                            onClick={() => {
                              if (user?.isVerified) return;

                              openModal("CHECK_EMAIL_FOR_VERIFICATION", {
                                email: user.email,
                              });
                            }}
                            className="mt-0 hidden md:block text-sm xl:text-base font-body font-medium text-link-1 underline cursor-pointer"
                          >
                            Upgrade Now
                          </CustomLink>
                        </div>
                      </div>
                    </div>
                  )}
                  <UserDropdown
                    isAdmin={user?.role?.includes(Role.ADMIN)}
                    user={{
                      name: user.firstName + " " + user.lastName,
                      email: user.email,
                      isVerified: user?.isVerified ?? false,
                      profilePicture: user?.profilePicture,
                    }}
                  />
                </div>
              ) : (
                <SignInButton onClick={handleSignIn} />
              )
            ) : null}

            <button
              type="button"
              onClick={() => setMenuOpen((prev) => !prev)}
              className="flex h-11 w-11 items-center justify-center rounded-full bg-white shadow-button md:hidden"
              aria-label="Toggle menu"
              aria-expanded={menuOpen}
            >
              <span className="relative block h-4 w-5">
                <span
                  className={`absolute left-0 h-0.5 w-5 rounded-full bg-link transition-all ${
                    menuOpen ? "top-2 rotate-45" : "top-0"
                  }`}
                />
                <span
                  className={`absolute left-0 top-2 h-0.5 w-5 rounded-full bg-link transition-all ${
                    menuOpen ? "opacity-0" : "opacity-100"
                  }`}
                />
                <span
                  className={`absolute left-0 h-0.5 w-5 rounded-full bg-link transition-all ${
                    menuOpen ? "top-2 -rotate-45" : "top-4"
                  }`}
                />
              </span>
            </button>
          </div>
        </div>

        <div
          className={`overflow-hidden transition-all duration-300 md:hidden ${
            menuOpen ? "max-h-90 opacity-100" : "max-h-0 opacity-0"
          }`}
        >
          <div className="mt-3 rounded-3xl border border-badge bg-white/90 p-4 backdrop-blur-xl">
            <nav className="flex flex-col gap-2">
              {nav.map(([href, label]) => {
                const isActive =
                  href === "/" ? pathname === "/" : pathname.startsWith(href);

                return (
                  <CustomLink
                    key={href}
                    href={href}
                    onClick={() => setMenuOpen(false)}
                    className={`rounded-2xl px-4 py-3 font-heading text-base font-medium transition-all ${
                      isActive
                        ? "bg-[#f3edff] text-link"
                        : "text-text hover:bg-[#f3edff] hover:text-link"
                    }`}
                  >
                    {label}
                  </CustomLink>
                );
              })}
            </nav>
          </div>
        </div>
      </div>
    </header>
  );
}

function SignInButton({ className = "", onClick }: SignInButtonProps) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`gradient1 inline-flex cursor-pointer rounded-full p-px text-link shadow-button transition-all duration-300 hover:scale-[1.02] ${className}`}
    >
      <span className="flex w-full items-center justify-center gap-0 md:gap-2 rounded-full bg-white md:py-1.5 md:ps-2.5 md:pr-5 text-center font-body text-base font-medium leading-none tracking-normal">
        <span className="gradient1 flex h-8.5 w-8.5 items-center justify-center rounded-xl">
          <svg
            width="16"
            height="19"
            viewBox="0 0 16 19"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            aria-hidden="true"
          >
            <path
              d="M7.6593 7.65917C9.5923 7.65917 11.1593 6.09217 11.1593 4.15917C11.1593 2.22617 9.5923 0.659168 7.6593 0.659168C5.72631 0.659168 4.1593 2.22617 4.1593 4.15917C4.1593 6.09217 5.72631 7.65917 7.6593 7.65917Z"
              stroke="white"
              strokeWidth="1.31283"
            />
            <path
              d="M14.6593 14.2216C14.6593 16.396 14.6593 18.1591 7.6593 18.1591C0.659302 18.1591 0.659302 16.396 0.659302 14.2216C0.659302 12.0473 3.79355 10.2841 7.6593 10.2841C11.5251 10.2841 14.6593 12.0473 14.6593 14.2216Z"
              stroke="white"
              strokeWidth="1.31833"
            />
          </svg>
        </span>
        <span className="hidden md:block">Sign In</span>
      </span>
    </button>
  );
}

function UserDropdown({
  user,
  isAdmin,
}: {
  user: {
    name: string;
    email: string;
    avatar?: string;
    isVerified: boolean;
    profilePicture: string;
  };
  isAdmin: boolean;
}) {
  const [open, setOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const { openModal } = useModal();

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  return (
    <div className="relative" ref={dropdownRef}>
      {/* Avatar Trigger */}

      <div
        className="relative h-11 w-11 xl:h-15 xl:w-15 overflow-hidden rounded-full border-2 xl:border-3 border-badge cursor-pointer"
        onClick={() => setOpen((prev) => !prev)}
      >
        <UserImage
          src={user.profilePicture || "/images/user-default.svg"}
          alt="Profile"
          className="object-cover w-full h-full"
        />
      </div>
      {open && (
        <div className="absolute right-0 mt-2 w-56 rounded-2xl border border-white/60 bg-white p-2 shadow-button">
          {/* User Info */}
          <div className="border-b border-gray-100 px-3 py-2 mb-2">
            <p className="font-heading text-sm font-semibold text-heading">
              {user.name}
            </p>
            <p className="font-body text-xs text-text truncate">{user.email}</p>
          </div>
          {/* Menu Items */}
          {isAdmin ? (
            <>
              <CustomLink
                href="/admin"
                onClick={() => setOpen(false)}
                className="flex items-center gap-2 rounded-xl px-3 py-2 text-sm text-text transition-all hover:bg-[#f3edff] hover:text-link"
              >
                Admin Dashboard
              </CustomLink>
            </>
          ) : (
            <>
              <CustomLink
                href={user.isVerified ? "/dashboard" : "#"}
                onClick={() => {
                  setOpen(false);
                  if (user.isVerified) return;

                  openModal("CHECK_EMAIL_FOR_VERIFICATION", {
                    email: user.email,
                  });
                }}
                className="flex items-center gap-2 rounded-xl px-3 py-2 text-sm text-text transition-all hover:bg-[#f3edff] hover:text-link"
              >
                Dashboard
              </CustomLink>

              <CustomLink
                href={user.isVerified ? "/profile" : "#"}
                onClick={() => {
                  setOpen(false);
                  if (user.isVerified) return;

                  openModal("CHECK_EMAIL_FOR_VERIFICATION", {
                    email: user.email,
                  });
                }}
                className="flex items-center gap-2 rounded-xl px-3 py-2 text-sm text-text transition-all hover:bg-[#f3edff] hover:text-link"
              >
                Profile
              </CustomLink>
            </>
          )}

          {/* Logout */}
          <div className="mt-2 border-t border-gray-100 pt-2">
            <button
              onClick={() => {
                openModal("LOGOUT", {});
              }}
              type="button"
              className="cursor-pointer flex w-full items-center gap-2 rounded-xl px-3 py-2 text-sm text-danger transition-all hover:bg-danger-light"
            >
              Sign Out
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
