"use client";
import { useRouter } from "next/router";
import { useSession } from "~/providers/SessionProvider";
import { api } from "~/utils/api";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "~/components/ui/dropdown-menu";
import { Button } from "~/components/ui/button";
import Link from "next/link";
import { LogIn, LogOut } from "lucide-react";
import { useTranslation } from "~/providers/I18nProvider";
import { cn } from "~/lib/utils";
import { IconMatrix, type IconType } from "~/components/IconComponents";
import { usePathname } from "next/navigation";
import { UserAvatar } from "~/components/user_avatar";
import { LoadingSpinner } from "~/components/spinner";

type LoginButtonProps = {
  open: boolean;
  setOpen: (status: boolean) => void;
  setSidebar: (status: boolean) => void;
  inSidebar?: boolean;
};

export const UserHeaderSection = ({
  open,
  setOpen,
  setSidebar,
  inSidebar,
}: LoginButtonProps) => {
  const router = useRouter();
  const session = useSession();
  const { t } = useTranslation();
  const path = usePathname();
  const utils = api.useUtils();
  const { mutate: logout } = api.auth.logoutUser.useMutation({
    onSuccess: async () => {
      if (path.startsWith("/area-riservata")) {
        await router.push("/");
      } else {
        router.reload();
      }

      await utils.auth.getSession.invalidate();
    },
  });

  if (session.status === "pending") {
    return (
      <div className="flex items-center px-3 py-2">
        <LoadingSpinner className="size-5" />
      </div>
    );
  }

  return (
    <div className="flex items-center">
      {!session || !session.user ? (
        <Button
          aria-label="Login Button"
          variant="ghost"
          onClick={async () => {
            await router.push({
              pathname: "/login",
              query: { redirect: router.asPath },
            });
            setSidebar(false);
          }}
          className="flex h-[46px] w-full items-center justify-center gap-x-1 rounded-lg p-2"
        >
          {inSidebar && t.auth.login.titolo}

          <LogIn className="size-5" />
        </Button>
      ) : (
        <DropdownMenu open={open} onOpenChange={setOpen}>
          <DropdownMenuTrigger asChild>
            <Button
              aria-label="User Profile Button"
              variant="ghost"
              className="flex h-[46px] w-full items-center justify-center gap-x-1 rounded-full p-2 font-medium"
            >
              <UserAvatar
                username={session.user.username}
                userId={session.user.id}
                className="size-10"
              />
              {inSidebar ? (
                <span>{session.user.username}</span>
              ) : (
                <span className="navqry:block hidden">
                  {session.user.username}
                </span>
              )}
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="w-56" align="end" forceMount>
            {session.user.isAdmin ? (
              <>
                <DropdownMenuLabel className="font-normal">
                  <div className="flex flex-col space-y-1">
                    <p className="text-sm leading-none font-medium">
                      {session.user.username}
                    </p>
                    <p className="text-muted-foreground text-xs leading-none">
                      Amministratore
                    </p>
                  </div>
                </DropdownMenuLabel>

                <DropdownMenuSeparator />

                <Items items={t.nav.loginMenuAdmin} setOpen={setOpen} />

                <DropdownMenuSeparator />
                <DropdownMenuItem
                  className="flex cursor-pointer items-center gap-3 px-2 py-1.5"
                  aria-label="Logout Button"
                  onClick={() => {
                    logout();
                  }}
                >
                  <LogOut className="size-6" />
                  {t.auth.login.logout}
                </DropdownMenuItem>
              </>
            ) : (
              <>
                <DropdownMenuLabel className="font-normal">
                  <div className="flex flex-col space-y-1">
                    <p className="text-sm leading-none font-medium">
                      {session.user.username}
                    </p>
                    <p className="text-muted-foreground text-xs leading-none">
                      {session.user.email}
                    </p>
                  </div>
                </DropdownMenuLabel>

                <DropdownMenuSeparator />
                <Items items={t.nav.loginMenuUser} setOpen={setOpen} />
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  aria-label="Logout Button"
                  className="flex cursor-pointer items-center gap-3 px-2 py-1.5"
                  onClick={() => {
                    logout();
                  }}
                >
                  <LogOut className="size-6" />
                  {t.auth.login.logout}
                </DropdownMenuItem>
              </>
            )}
          </DropdownMenuContent>
        </DropdownMenu>
      )}
    </div>
  );
};

const Items = ({
  items,
  setOpen,
}: {
  items: {
    title: string;
    icon: { icon: IconType; className: string };
    href: string;
  }[];
  setOpen: (status: boolean) => void;
}) => {
  return (
    <DropdownMenuGroup>
      {items?.map((item, idx) => (
        <DropdownMenuItem key={idx} className="p-0">
          <Link
            aria-label={`Link to ${item.title}`}
            onClick={() => setOpen(false)}
            href={item.href}
            className="flex h-full w-full items-center gap-3 px-2 py-1.5"
          >
            <IconMatrix
              type={item.icon.icon}
              className={cn("size-6", item.icon.className)}
            />

            {item.title}
          </Link>
        </DropdownMenuItem>
      ))}
    </DropdownMenuGroup>
  );
};
