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

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 { status, user } = 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 (status === "LOADING") {
		return (
			<div className="flex items-center px-3 py-2">
				<LoadingSpinner className="size-5" />
			</div>
		);
	}

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

					<LogIn />
				</Button>
			) : (
				<DropdownMenu onOpenChange={setOpen} open={open}>
					<DropdownMenuTrigger asChild>
						<Button
							aria-label="User Profile Button"
							className="flex h-10 w-full items-center justify-center gap-x-1 rounded-full py-2 navqry:pr-2 pr-0 pl-0 font-medium"
							variant="ghost"
						>
							<UserAvatar
								className="size-10"
								userId={user.id}
								username={user.username}
							/>
							{inSidebar ? (
								<span>{user.username}</span>
							) : (
								<span className="navqry:block hidden">{user.username}</span>
							)}
						</Button>
					</DropdownMenuTrigger>
					<DropdownMenuContent align="end" className="w-56" forceMount>
						{user.isAdmin ? (
							<>
								<DropdownMenuLabel className="font-normal">
									<div className="flex flex-col space-y-1">
										<p className="font-medium text-sm leading-none">
											{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
									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>
							</>
						) : (
							<>
								<DropdownMenuLabel className="font-normal">
									<div className="flex flex-col space-y-1">
										<p className="font-medium text-sm leading-none">
											{user.username}
										</p>
										<p className="text-muted-foreground text-xs leading-none">
											{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) => (
				<DropdownMenuItem className="p-0" key={item.href}>
					<Link
						aria-label={`Link to ${item.title}`}
						className="flex h-full w-full items-center gap-3 px-2 py-1.5"
						href={item.href}
						onClick={() => setOpen(false)}
					>
						<IconMatrix
							className={cn("size-6", item.icon.className)}
							type={item.icon.icon}
						/>

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