import { ArrowRight, BadgePlus, LogIn } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/router";
import toast from "react-hot-toast";
import { ContattoAnnuncio } from "~/components/annuncio-interactions/contatto_modal";
import LoadingButton from "~/components/custom_ui/loading-button";
import { Button, buttonVariants } from "~/components/ui/button";
import { cn } from "~/lib/utils";
import { useAnnuncio } from "~/providers/AnnuncioProvider";
import type { SessionContextType } from "~/providers/SessionProvider";
import type { AnnunciId } from "~/schemas/public/Annunci";
import type { UsersId } from "~/schemas/public/Users";
import { api } from "~/utils/api";

export const AnnuncioInteractions = ({
	session,
	disabled,
}: {
	session: SessionContextType;
	disabled?: boolean;
}) => {
	const router = useRouter();
	const { id, tipo } = useAnnuncio();

	if (disabled) {
		return (
			<div className="w-full rounded-md bg-red-500 p-2 text-center font-semibold text-base text-white">
				Richieste Temporaneamente disattivate
			</div>
		);
	}
	return (
		<div className="flex w-full flex-col justify-around gap-3 md:gap-5">
			{session.user ? (
				tipo ? (
					<ServizioInteraction
						annuncioId={id}
						tipologia={tipo}
						userId={session.user.id}
					/>
				) : (
					<span>Errore</span>
				)
			) : (
				<div className="flex w-full flex-col gap-2">
					<ContattoAnnuncio />
					<span className="w-full text-center text-sm">oppure</span>
					<Link
						aria-label="Login"
						className={cn(buttonVariants({ variant: "default" }))}
						href={{
							pathname: "/login",
							query: { redirect: router.asPath },
						}}
					>
						<LogIn className="mr-1 size-7" /> Accedi se hai un account
					</Link>
				</div>
			)}
		</div>
	);
};

const ServizioInteraction = ({
	userId,
	tipologia,
	annuncioId,
}: {
	userId: UsersId;
	tipologia: string;
	annuncioId: AnnunciId;
}) => {
	const { data: servizio, isLoading } =
		api.servizio.AnnuncioServizioTipologiaMatch.useQuery({
			annuncioId,
			tipologia,
			userId,
		});

	if (isLoading) return <LoadingButton className="w-full" loading />;
	if (
		servizio === undefined ||
		servizio.status === "invalid" ||
		servizio.status === "not_found"
	) {
		return (
			<div>
				<p>Non hai un servizio attivo</p>
			</div>
		);
	}

	if (servizio.status === "already_saved") {
		return (
			<div className="flex w-full flex-col gap-2">
				<div className="w-full text-center font-semibold text-green-500">
					Annuncio già salvato!
				</div>
				<Link
					aria-label="Vai alla tua area riservata"
					href={`/area-riservata/dashboard`}
				>
					<Button className="flex w-full items-center gap-2" variant="success">
						Vai alla tua area riservata <ArrowRight />
					</Button>
				</Link>
			</div>
		);
	}

	return <InteressatoButton annuncioId={annuncioId} />;
};

const InteressatoButton = ({ annuncioId }: { annuncioId: AnnunciId }) => {
	const { data: hasInterest, isLoading } =
		api.intrests.hasUserInterest.useQuery({
			annuncioId,
		});
	const utils = api.useUtils();
	const { mutate: add } = api.intrests.addIntrest.useMutation({
		onSuccess: async () => {
			await utils.intrests.hasUserInterest.invalidate({
				annuncioId,
			});
			toast.success("Richiesta di interesse inviata con successo!");
		},
	});

	if (isLoading || hasInterest === undefined) {
		return (
			<Button className="flex w-full items-center gap-2" disabled>
				<BadgePlus className="size-6" />
				Caricamento...
			</Button>
		);
	}
	if (hasInterest) {
		return (
			<span className="flex w-full items-center justify-center gap-2 rounded-md bg-green-500 p-2 font-semibold text-sm text-white">
				<BadgePlus className="inline size-5" />
				Hai già mandato una richiesta
			</span>
		);
	}

	return (
		<Button
			aria-label="Sono interessato"
			className="flex w-full items-center gap-2"
			//size="xl"
			onClick={() => {
				add({
					annuncioId,
				});
			}}
			variant="info"
		>
			<BadgePlus className="size-6" />
			Sono interessato
		</Button>
	);
};

export const InteressatoButtonBatchV = ({
	annuncioId,
	hasInterest,
}: {
	annuncioId: AnnunciId;
	hasInterest: boolean;
}) => {
	const utils = api.useUtils();
	const { mutate: add } = api.intrests.addIntrest.useMutation({
		onSuccess: async () => {
			await utils.intrests.getUserInterests.invalidate();
			toast.success("Richiesta di interesse inviata con successo!");
		},
	});

	if (hasInterest) {
		return (
			<span className="flex w-full items-center justify-center gap-2 rounded-md bg-green-500 p-2 font-semibold text-sm text-white">
				<BadgePlus className="inline size-5" />
				Hai già mandato una richiesta
			</span>
		);
	}

	return (
		<Button
			aria-label="Sono interessato"
			className="flex w-full items-center gap-2"
			//size="xl"
			onClick={() => {
				add({
					annuncioId,
				});
			}}
			variant="info"
		>
			<BadgePlus className="size-6" />
			Sono interessato
		</Button>
	);
};
