"use client";

import {
  Navbar as BaseNavbar,
  NavbarBrand,
  NavbarContent,
  NavbarItem,
  NavbarMenu,
  NavbarMenuItem,
  NavbarMenuToggle,
  Avatar,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  DropdownTrigger,
} from "@nextui-org/react";
import { usePathname, useRouter } from "next/navigation";
import {
  FaAlignJustify,
  FaArrowRightFromBracket,
  FaPeopleGroup,
  FaTableList,
  FaUser,
  FaUserPlus,
} from "react-icons/fa6";
import { useEffect, useState } from "react";
import Link from "next/link";
import { LuLogOut } from "react-icons/lu";

import PFRDefaultLogo from "@/components/common/sprites/pfr-default-logo-sprite";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import PFRSamLogo from "@/components/common/sprites/pfr-sam-logo-sprite";
import Button, { ButtonComponentProps } from "@/components/common/button";
import { NAVBAR_LINKS_PARTICIPANT } from "@/constants/ui-helpers";
import ThemeSwitcher from "@/components/common/theme-switcher";
import { deleteSession } from "@/lib/user-session";

type NavbarAvatarProps = {
  firstName: string;
  lastName: string;
  userInitials: string;
  userEmail: string;
  onClickLogout: () => void;
};

type ParticipantNavbarProps = {
  firstName: string;
  lastName: string;
  isLoggedIn: boolean;
  userEmail: string;
  userInitials: string;
};

export type NavbarButtonProps = {
  href: string;
} & ButtonComponentProps;

function NavbarAvatar({
  userInitials,
  userEmail,
  firstName,
  lastName,
  onClickLogout,
}: NavbarAvatarProps) {
  const dropdownMenuItems = [
    {
      key: "signed-in-info",
      label: "Signed in information",
      children: (
        <>
          <p className="font-medium">
            {firstName} {lastName}
          </p>
          <span>({userEmail})</span>
        </>
      ),
    },
    {
      key: "profile",
      label: "My profile",
      href: INTERNAL_PAGES.participant.profile.main,
      children: "My profile",
    },
    {
      key: "preferences",
      label: "Preferences",
      href: INTERNAL_PAGES.participant.profile.preferences,
      children: "Preferences",
    },
    {
      key: "accountSettings",
      label: "Account settings",
      href: INTERNAL_PAGES.participant.profile.accountSettings,
      children: "Account settings",
    },
    {
      key: "logout",
      label: "Logout",
      color: "danger",
      children: (
        <Button
          fullWidth
          btnLabel="Logout"
          className="bg-red-100 text-red-800"
          endContent={<LuLogOut />}
          size="sm"
          variant="flat"
          onClick={() => onClickLogout()}
        />
      ),
    },
  ];

  return (
    <NavbarItem>
      <Dropdown placement="bottom-end">
        <DropdownTrigger>
          <Avatar
            isBordered
            as="button"
            className="transition-transform"
            classNames={{
              base: "size-3 text-white bg-[#383934]",
              name: "font-semibold font-noto",
            }}
            name={userInitials}
            size="sm"
          />
        </DropdownTrigger>
        <DropdownMenu aria-label="Profile Actions" variant="flat">
          {dropdownMenuItems.map((item) => (
            <DropdownItem
              key={item.key}
              href={item.href}
              textValue={item.label}
            >
              {item.children}
            </DropdownItem>
          ))}
        </DropdownMenu>
      </Dropdown>
    </NavbarItem>
  );
}

function ParticipantNavbar({
  isLoggedIn,
  userInitials,
  userEmail,
  firstName,
  lastName,
}: ParticipantNavbarProps) {
  const router = useRouter();
  const pathname = usePathname();
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const isParticipantHome = pathname === INTERNAL_PAGES.participant.homepage;
  const isB2BHome = pathname === INTERNAL_PAGES.participant.businessPanelHome;
  const isCampaigns = pathname.startsWith(INTERNAL_PAGES.participant.campaign);

  const handleLogout = () => {
    deleteSession();
  };

  useEffect(() => {
    setIsMenuOpen(false);
  }, [pathname]);

  return (
    <BaseNavbar
      as="nav"
      classNames={{
        base: "bg-b2b-light dark:bg-b2b-dark pt-2 z-50",
      }}
      isMenuOpen={isMenuOpen}
      maxWidth="full"
      onMenuOpenChange={setIsMenuOpen}
    >
      {/* Navbar links */}
      <NavbarContent className="hidden xl:flex" justify="start">
        {NAVBAR_LINKS_PARTICIPANT.map((link) => {
          const howItWorksHref = isLoggedIn
            ? INTERNAL_PAGES.participant.howItWorks.homepage
            : link.href;

          return (
            <NavbarItem key={link.title}>
              <Link
                key={link.title}
                className="text-black dark:text-white cursor-pointer font-inter font-semibold text-sm relative group"
                href={
                  link.title === "How it works" ? howItWorksHref : link.href
                }
              >
                {link.title}
                <span className="bg-black dark:bg-white block h-1 transform scale-x-0 group-hover:scale-x-100 transition-transform duration-200 origin-left"></span>
              </Link>
            </NavbarItem>
          );
        })}
      </NavbarContent>

      {/* Navbar brand*/}
      <NavbarBrand className="flex-grow-0">
        <Link
          className="hidden xl:flex"
          href={INTERNAL_PAGES.participant.homepage}
        >
          <PFRDefaultLogo width={100} />
        </Link>
        <Link
          className="xl:hidden flex"
          href={INTERNAL_PAGES.participant.homepage}
        >
          <PFRSamLogo width={40} />
        </Link>
      </NavbarBrand>

      {/* Navbar buttons */}
      <NavbarContent className="gap-2 hidden xl:flex" justify="end">
        {isLoggedIn && (
          <NavbarItem>
            <Button
              fullWidth
              btnLabel="Apply for opportunities"
              customVariant="no-border"
              size="sm"
              startContent={<FaTableList className="size-3" />}
              onClick={() =>
                router.push(INTERNAL_PAGES.participant.opportunities.main)
              }
            />
          </NavbarItem>
        )}

        {!isLoggedIn && !isCampaigns && (
          <>
            <NavbarItem className="hidden xl:flex">
              <Button
                btnLabel="Client services"
                customVariant="no-border"
                size="sm"
                startContent={<FaPeopleGroup className="size-3" />}
                onClick={() => router.push(INTERNAL_PAGES.client.homepage)}
              />
            </NavbarItem>
            <NavbarItem className="hidden xl:flex">
              <Button
                fullWidth
                btnLabel={
                  isB2BHome ? "Join our business panel" : "Join our community"
                }
                customVariant={isB2BHome ? "b2b" : "primary"}
                size="sm"
                startContent={<FaUserPlus />}
                onClick={() =>
                  router.push(INTERNAL_PAGES.participant.signup.main)
                }
              />
            </NavbarItem>
          </>
        )}

        {!isLoggedIn && (
          <NavbarItem className="hidden xl:flex">
            <Button
              btnLabel="Log in"
              customVariant="transparent"
              size="sm"
              startContent={<FaUser className="size-3" />}
              onClick={() => router.push(INTERNAL_PAGES.participant.login)}
            />
          </NavbarItem>
        )}

        {isLoggedIn && (
          <NavbarAvatar
            firstName={firstName}
            lastName={lastName}
            userEmail={userEmail}
            userInitials={userInitials}
            onClickLogout={handleLogout}
          />
        )}

        <NavbarItem>
          <ThemeSwitcher />
        </NavbarItem>
      </NavbarContent>
      <NavbarMenuToggle
        aria-label={isMenuOpen ? "Close menu" : "Open menu"}
        className="xl:hidden ps-2 pe-8"
        icon={
          <div>
            <FaAlignJustify className="size-6 text-black dark:text-white" />
          </div>
        }
      />
      {/* Mobile menu sidebar */}
      <NavbarMenu
        className={`${
          isParticipantHome ? "mt-4" : "mt-0"
        } bg-b2b-light dark:bg-b2b-dark flex flex-col space-y-8 pb-12`}
      >
        <div
          className={`${
            isParticipantHome ? "pt-12" : "pt-4"
          } flex flex-col space-y-4`}
        >
          {NAVBAR_LINKS_PARTICIPANT.map((item, index) => (
            <NavbarMenuItem
              key={`${item}-${index}`}
              className="font-noto text-sm font-bold tracking-tight"
            >
              <Link href={item.href}>{item.title}</Link>
            </NavbarMenuItem>
          ))}
        </div>
        <NavbarMenuItem className="font-noto text-sm font-bold tracking-tight flex items-center">
          Switch theme
          <ThemeSwitcher />
        </NavbarMenuItem>
        {!isLoggedIn && (
          <NavbarMenuItem className="font-noto text-sm font-bold tracking-tight">
            <Link href={INTERNAL_PAGES.client.homepage}>
              Looking for participant recruitment?
            </Link>
          </NavbarMenuItem>
        )}
        <div className="flex flex-col items-center">
          {!isLoggedIn && (
            <div className="flex flex-col py-2 space-y-2 w-full">
              <NavbarMenuItem>
                <Button
                  fullWidth
                  btnLabel={
                    isB2BHome ? "Join our business panel" : "Join our community"
                  }
                  customVariant={isB2BHome ? "b2b" : "primary"}
                  size="sm"
                  startContent={<FaUserPlus />}
                  onClick={() =>
                    router.push(INTERNAL_PAGES.participant.signup.main)
                  }
                />
              </NavbarMenuItem>
              <NavbarMenuItem>
                <Button
                  fullWidth
                  btnLabel="Log in"
                  customVariant="transparent"
                  size="sm"
                  startContent={<FaUser className="size-3" />}
                  onClick={() => router.push(INTERNAL_PAGES.participant.login)}
                />
              </NavbarMenuItem>
            </div>
          )}
          {isLoggedIn && (
            <div className="flex flex-col py-2 space-y-2 w-full">
              <NavbarMenuItem>
                <Button
                  fullWidth
                  btnLabel="Current opportunities"
                  customVariant="primary"
                  size="sm"
                  startContent={<FaTableList className="size-3" />}
                  onClick={() =>
                    router.push(INTERNAL_PAGES.participant.opportunities.main)
                  }
                />
              </NavbarMenuItem>
              <NavbarMenuItem>
                <Button
                  fullWidth
                  btnLabel="Logout"
                  customVariant="transparent"
                  size="sm"
                  startContent={<FaArrowRightFromBracket className="size-3" />}
                  onClick={handleLogout}
                />
              </NavbarMenuItem>
            </div>
          )}
          <Link href={INTERNAL_PAGES.participant.homepage}>
            <PFRDefaultLogo width={200} />
          </Link>
          <span className="text-xs text-center font-noto">
            Specialised in providing participant recruitment for user research
            and usability testing.
          </span>
        </div>
      </NavbarMenu>
    </BaseNavbar>
  );
}

export default ParticipantNavbar;
