import {
	CircleCheck,
	CircleUser,
	Navigation,
	Phone,
	TriangleAlert,
} from "lucide-react";
import Link from "next/link";
import { useMemo } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "~/providers/I18nProvider";
import { useServizio, useServizioAnnuncio } from "~/providers/ServizioProvider";
import type { UsersStorageUserStorageId } from "~/schemas/public/UsersStorage";
import { api } from "~/utils/api";
import {
	Credenza,
	CredenzaBody,
	CredenzaClose,
	CredenzaContent,
	CredenzaDescription,
	CredenzaFooter,
	CredenzaHeader,
	CredenzaTitle,
	CredenzaTrigger,
} from "../custom_ui/credenza";
import { LoadingPage } from "../loading";
import { WhatsAppIcon2 } from "../svgs";
import { Button } from "../ui/button";
import { type UploadCallback, UploadModal } from "../upload_modal";

export const ContattiProprietarioModal = () => {
	const { servizio } = useServizio();
	const { data } = useServizioAnnuncio();
	const { t } = useTranslation();
	return (
		<Credenza>
			<CredenzaTrigger asChild>
				{data.open_contatti_at != null ? (
					<Button
						aria-label="Vedi contatti proprietario"
						className="flex w-fit items-center gap-2"
						variant="success"
					>
						<CircleUser className="size-7" />
						Vedi i contatti
					</Button>
				) : (
					<Button
						aria-label="Contatta proprietario"
						className="flex w-fit items-center gap-2"
						variant="warning"
					>
						<CircleUser className="size-7" />
						Ottieni i contatti
					</Button>
				)}
			</CredenzaTrigger>
			<CredenzaContent className="max-h-[90vh]">
				<CredenzaHeader>
					<CredenzaTitle>{t.contatto.title}</CredenzaTitle>
					<CredenzaDescription className="sr-only">
						{t.contatto.descrizione}
					</CredenzaDescription>
				</CredenzaHeader>
				{servizio.doc_personale_fronte == null ||
				servizio.doc_personale_retro == null ? (
					<DocCheckpoint />
					// biome-ignore lint/style/noNestedTernary: <this is fine>
				) : data.open_contatti_at == null ? (
					<PreUnlock />
				) : (
					<PostUnlock />
				)}
			</CredenzaContent>
		</Credenza>
	);
};

const DocComponent = ({
	docInfo,
	cb,
}: {
	docInfo: {
		storageId: string;
		ref: UsersStorageUserStorageId | null;
	} | null;
	cb: UploadCallback;
}) => {
	const { isAdmin, userId } = useServizio();

	if (!docInfo?.storageId) {
		return <UploadModal cb_onUpload={cb} isAdmin={isAdmin} userId={userId} />;
	}
	return (
		<div className="flex items-center gap-2 text-green-500">
			<CircleCheck className="size-5" />
			<span>Documento caricato</span>
		</div>
	);
};

const DocCheckpoint = () => {
	const { t } = useTranslation();
	const { userId, servizio } = useServizio();
	const utils = api.useUtils();
	const { mutate } = api.servizio.updateServizio.useMutation({
		onSuccess: async () => {
			await utils.servizio.getAllServizioAnnunci.invalidate({
				userId,
			});
			await utils.storage.retrieveUserFileData.invalidate({ userId });
			await utils.servizio.getServizio.invalidate({
				servizioId: servizio.servizio_id,
			});
		},
		onError: (err) => {
			toast.error(`Errore aggiornamento servizio: ${err.message}`);
		},
	});
	return (
		<>
			<CredenzaBody className="max-h-[80vh] overflow-auto pb-5">
				<div className="space-y-5">
					<p>Devi ancora caricare un tuo documento</p>
					<div className="flex items-center gap-2">
						Fronte documento:{" "}
						<DocComponent
							cb={({ userStorageIds }) =>
								userStorageIds.length > 0 &&
								mutate({
									servizioId: servizio.servizio_id,
									data: {
										doc_personale_fronte_ref: userStorageIds[0],
									},
								})
							}
							docInfo={servizio.doc_personale_fronte}
						/>
					</div>
					<div className="flex items-center gap-2">
						Retro documento:{" "}
						<DocComponent
							cb={({ userStorageIds }) =>
								userStorageIds.length > 0 &&
								mutate({
									servizioId: servizio.servizio_id,
									data: {
										doc_personale_retro_ref: userStorageIds[0],
									},
								})
							}
							docInfo={servizio.doc_personale_retro}
						/>
					</div>

					<br />
					<br />
					<p className="text-muted-foreground text-sm">
						I tuoi dati saranno conservati solamente per la durata del servizio,
						in conformità con la nostra{" "}
						<Link className="underline" href="/privacy-policy" target="_blank">
							Informativa sulla Privacy
						</Link>
					</p>
				</div>
			</CredenzaBody>
			<CredenzaFooter>
				<CredenzaClose asChild>
					<Button aria-label="Chiudi modal credenza" variant="outline">
						{t.chiudi}
					</Button>
				</CredenzaClose>
			</CredenzaFooter>
		</>
	);
};

const PreUnlock = () => {
	const { userId, servizioId } = useServizio();
	const { annuncioId } = useServizioAnnuncio();
	const { t } = useTranslation();

	const utils = api.useUtils();

	const { mutate } = api.servizio.unlockServizioContatti.useMutation({
		onError: (err) => {
			toast.error(err.message, {
				id: "unlock-contacts",
			});
		},
		onMutate: () => {
			toast.loading("Caricamento ...", {
				id: "unlock-contacts",
			});
		},
		onSuccess: async (data) => {
			if (!data) {
				toast.error("Limite di sblocchi raggiunto", {
					id: "unlock-contacts",
				});
				return;
			}
			toast.success("Successo", {
				id: "unlock-contacts",
			});
			await utils.servizio.getAllServizioAnnunci.invalidate({
				userId,
			});
		},
	});

	const d = new Date();
	const tooEarly = d.getHours() < 9;
	const tooLate = d.getHours() >= 20;
	return (
		<>
			<CredenzaBody className="max-h-[80vh] overflow-auto pb-5">
				<div className="space-y-5">
					<p>{t.contatto.disclaimer}</p>
					<p>{t.contatto.disclaimer2}</p>
					<p className="text-muted-foreground text-xs">
						{t.contatto.disclaimer3}
					</p>
					{(tooEarly || tooLate) && (
						<div className="flex items-center gap-2 rounded-md bg-yellow-200 p-2">
							<TriangleAlert className="size-8" />
							{/*TODO testare */}
							<p>
								Il proprietario riceverà la notifica alle ore 9.00{" "}
								{tooLate && "di domani"}
							</p>
						</div>
					)}
				</div>
			</CredenzaBody>
			<CredenzaFooter>
				<Button
					aria-label="Contatta proprietario"
					onClick={() =>
						mutate({
							annuncioId,
							servizioId,
						})
					}
					variant="success"
				>
					{t.accetta}
				</Button>

				<CredenzaClose asChild>
					<Button aria-label="Chiudi modal credenza" variant="outline">
						{t.chiudi}
					</Button>
				</CredenzaClose>
			</CredenzaFooter>
		</>
	);
};

function getNavigationUrl(lat: string, lon: string): string {
	if (typeof window !== "undefined") {
		const isIOS =
			navigator.userAgent.toUpperCase().includes("MAC") ||
			navigator.userAgent.toUpperCase().includes("IPAD") ||
			navigator.userAgent.toUpperCase().includes("IPHONE") ||
			navigator.userAgent.toUpperCase().includes("IOS") ||
			navigator.userAgent.toUpperCase().includes("IPOD");

		return `${isIOS ? "maps" : "https"}://www.google.com/maps/dir/?api=1&travelmode=driving&layer=traffic&destination=${lat},${lon}`;
	}
	return `https://www.google.com/maps/dir/?api=1&travelmode=driving&layer=traffic&destination=${lat},${lon}`;
}

const PostUnlock = () => {
	const { servizioId } = useServizio();
	const { annuncioId } = useServizioAnnuncio();
	const { data, isLoading } = api.annunci.getProprietarioData.useQuery({
		annuncioId,
		servizioId,
	});

	const { t } = useTranslation();

	// Memoize navigation URL
	const navigationUrl = useMemo(() => {
		if (!data?.propData || !data.propData.lat || !data.propData.lon)
			return undefined;
		return getNavigationUrl(data.propData.lat, data.propData.lon);
	}, [data?.propData]);

	if (isLoading) {
		return (
			<div className="flex justify-center">
				<LoadingPage />
			</div>
		);
	}
	if (!data || !data.propData) {
		return <p>{t.contatto.error}</p>;
	}
	return (
		<>
			<CredenzaBody className="max-h-[80vh] overflow-auto pb-5">
				<div className="flex flex-col gap-2">
					<h3 className="font-semibold">{t.contatto.propietario}:</h3>
					<p>
						{t.contatto.nome}: {data.propData.locatore}
					</p>
					<div className="flex items-center gap-2">
						<a
							className="flex items-center gap-2"
							href={`tel:${data.propData.numero}`}
						>
							<Phone />:
							<span className="text-blue-600 underline">
								{data.propData.numero}
							</span>
						</a>
						<Link
							href={`https://wa.me/${data.propData.numero}`}
							target="_blank"
						>
							<Button
								className="flex items-center gap-2"
								size="sm"
								variant="success"
							>
								<WhatsAppIcon2 className="size-4 fill-white" />
								WhatsApp
							</Button>
						</Link>
					</div>

					<br />
					<h3 className="font-semibold">{t.contatto.immobile}:</h3>
					<p>
						{t.contatto.indirizzo}: {data.propData.indirizzo},{" "}
						{data.propData.civico} {data.propData.comune} (
						{data.propData.provincia})
					</p>
					<a
						className="flex w-fit items-center gap-2 rounded-md border border-border px-3 py-2"
						href={navigationUrl}
						rel="noreferrer"
						target="_blank"
					>
						<Navigation /> <span>{t.contatto.apri_nav}</span>
					</a>
					<br />
					<p>
						{t.contatto.sbloccato_il}:{" "}
						{data.opened_at.toLocaleString("it", {
							day: "2-digit",
							hour: "2-digit",
							minute: "2-digit",
							month: "2-digit",
							year: "numeric",
						})}
					</p>
					<div className="flex items-center gap-2 rounded-md bg-red-500 p-2 text-white">
						<TriangleAlert className="size-8" />
						<div>
							<p>{t.contatto.contatta}</p>
							<p className="font-semibold">{t.contatto.orari}</p>
						</div>
					</div>
				</div>
			</CredenzaBody>
			<CredenzaFooter>
				<CredenzaClose asChild>
					<Button aria-label="Chiudi modal credenza" variant="outline">
						{t.chiudi}
					</Button>
				</CredenzaClose>
			</CredenzaFooter>
		</>
	);
};
