import { CircleUser, Navigation, Phone, TriangleAlert } from "lucide-react";
import Link from "next/link";
import { useMemo, useState } 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 { DocumentiUploadSection } from "../area-riservata/documenti_personali";
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";

export const ContattiProprietarioModal = () => {
	const { servizio } = useServizio();
	const [open, setOpen] = useState(false);
	const { data } = useServizioAnnuncio();
	const { t, locale } = useTranslation();
	const isUnlocked = data.open_contatti_at != null;

	const needsDocuments =
		!servizio.skipControlloDoc &&
		(!servizio.doc_personale_fronte || !servizio.doc_personale_retro);

	return (
		<Credenza
			onOpenChange={(o) => {
				setOpen(o);
			}}
			open={open}
		>
			<CredenzaTrigger asChild>
				{isUnlocked ? (
					<Button
						aria-label="Vedi contatti proprietario"
						className="w-full md:w-fit"
						variant="success"
					>
						<CircleUser />
						{locale === "it" ? "Contatti" : "Contacts"}
					</Button>
				) : (
					<Button
						aria-label="Contatta proprietario"
						className="w-full md:w-fit"
						variant="warning"
					>
						<CircleUser />
						{locale === "it" ? "Ottieni i contatti" : "Get contacts"}
					</Button>
				)}
			</CredenzaTrigger>
			<CredenzaContent className="max-h-[90vh] sm:max-w-2xl">
				<CredenzaHeader>
					<CredenzaTitle className="text-xl">{t.contatto.title}</CredenzaTitle>
					<CredenzaDescription className="sr-only">
						{t.contatto.descrizione}
					</CredenzaDescription>
				</CredenzaHeader>
				{needsDocuments ? (
					<DocCheckpoint />
				) : isUnlocked ? (
					<PostUnlock />
				) : (
					<PreUnlock />
				)}
			</CredenzaContent>
		</Credenza>
	);
};

const DocCheckpoint = () => {
	const { t, locale } = useTranslation();
	const { userId, servizio, isAdmin } = useServizio();
	const utils = api.useUtils();
	const { mutate, isPending } = api.users.editUserAnagrafica.useMutation({
		onSuccess: async () => {
			await utils.servizio.invalidate();
			await utils.storage.retrieveUserFileData.invalidate({ userId });
		},
		onError: (err) => {
			toast.error(`Errore aggiornamento servizio: ${err.message}`);
		},
	});
	const handleUpload = (
		field: "doc_personale_fronte_ref" | "doc_personale_retro_ref",
		id: UsersStorageUserStorageId,
	) => {
		mutate({
			userId,
			data: {
				[field]: id,
			},
		});
	};
	return (
		<>
			<CredenzaBody className="max-h-[80vh] overflow-auto pb-5">
				<div className="flex flex-col flex-wrap gap-4">
					<div>
						<p className="font-semibold">
							{locale === "it"
								? "Carica i tuoi documenti"
								: "Upload your documents"}
						</p>
						<p>
							{locale === "it"
								? "se si ha una scansione unica fronte/retro dei doc, caricarla due volte."
								: "if you have a single front/back scan of the documents, upload it twice."}
						</p>
					</div>

					<div className="flex flex-col flex-wrap justify-around gap-x-10 gap-y-4 sm:flex-row">
						<DocumentiUploadSection
							caricatoNote
							document={servizio.doc_personale_fronte}
							isAdmin={isAdmin}
							isPending={isPending}
							onRemove={() =>
								mutate({
									userId,
									data: { doc_personale_fronte_ref: null },
								})
							}
							onUpload={(id) => handleUpload("doc_personale_fronte_ref", id)}
							title="Documento d'identità - Fronte"
							userId={userId}
						/>

						<DocumentiUploadSection
							caricatoNote
							document={servizio.doc_personale_retro}
							isAdmin={isAdmin}
							isPending={isPending}
							onRemove={() =>
								mutate({
									userId,
									data: { doc_personale_retro_ref: null },
								})
							}
							onUpload={(id) => handleUpload("doc_personale_retro_ref", id)}
							title="Documento d'identità - Retro"
							userId={userId}
						/>
					</div>

					<p className="text-muted-foreground text-sm">
						{locale === "it"
							? "I tuoi dati saranno conservati solamente per la durata del servizio, in conformità con la nostra "
							: "Your data will be stored only for the duration of the service, in accordance with our "}
						<Link className="underline" href="/privacy-policy" target="_blank">
							{locale === "it" ? "Informativa sulla Privacy" : "Privacy Policy"}
						</Link>
					</p>
				</div>
			</CredenzaBody>
			<CredenzaFooter>
				<CredenzaClose asChild>
					<Button aria-label="Chiudi" disabled={isPending} variant="outline">
						{t.chiudi}
					</Button>
				</CredenzaClose>
			</CredenzaFooter>
		</>
	);
};

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

	const utils = api.useUtils();

	const { mutate, isPending } = 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.invalidate();
			},
		},
	);

	const currentHour = new Date().getHours();
	const isOutsideBusinessHours = currentHour < 9 || currentHour >= 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>
					{isOutsideBusinessHours && (
						<div className="flex items-center gap-2 rounded-md bg-yellow-200 p-2">
							<TriangleAlert className="size-8" />
							<p>
								{locale === "it"
									? "Il proprietario riceverà la notifica alle ore 9.00"
									: "The owner will receive the notification at 9:00 AM"}{" "}
								{currentHour >= 20 &&
									(locale === "it" ? "di domani" : "tomorrow")}
							</p>
						</div>
					)}
				</div>
			</CredenzaBody>
			<CredenzaFooter>
				<Button
					aria-label="Contatta proprietario"
					disabled={isPending}
					onClick={() =>
						mutate({
							annuncioId,
							servizioId,
						})
					}
					variant="success"
				>
					{t.accetta}
				</Button>

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

function getNavigationUrl(lat: string, lon: string): string {
	if (typeof window === "undefined") {
		return `https://www.google.com/maps/dir/?api=1&travelmode=driving&layer=traffic&destination=${lat},${lon}`;
	}
	const isIOS = /iPad|iPhone|iPod|Mac/.test(navigator.userAgent);
	const protocol = isIOS ? "maps" : "https";

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

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

	const { t } = useTranslation();

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

	if (isLoading) {
		return (
			<CredenzaBody className="flex justify-center p-8">
				<LoadingPage />
			</CredenzaBody>
		);
	}
	if (!data?.propData) {
		return (
			<CredenzaBody>
				<p className="text-destructive">{t.contatto.error}</p>
			</CredenzaBody>
		);
	}
	const { opened_at, propData } = data;
	return (
		<>
			<CredenzaBody className="max-h-[80vh] overflow-auto pb-5 sm:max-w-xl">
				<div className="space-y-10">
					{/* Proprietario Section */}
					{annuncio.stato === "Sospeso" ? (
						<section>
							<h3 className="mb-2 font-semibold">{t.contatto.propietario}:</h3>
							<p className="mb-2">{t.contatto.nome}: INFOALLOGGI (delegato)</p>
							<div className="flex flex-wrap items-center gap-5">
								<a
									className="flex items-center gap-2 text-blue-600 hover:underline"
									href={`tel:3453944827`}
								>
									<Phone className="size-4" />
									<span>+39 3453944827</span>
								</a>
								<Link href={`https://wa.me/3453944827`} target="_blank">
									<Button size="sm" variant="success">
										<WhatsAppIcon2 className="size-4 fill-white" />
										WhatsApp
									</Button>
								</Link>
							</div>
						</section>
					) : (
						<section>
							<h3 className="mb-2 font-semibold">{t.contatto.propietario}:</h3>
							<p className="mb-2">
								{t.contatto.nome}: {propData.locatore}
								{propData.tipo_locatore ? ` (${propData.tipo_locatore})` : ""}
							</p>
							<div className="flex flex-wrap items-center gap-5">
								<a
									className="flex items-center gap-2 text-blue-600 hover:underline"
									href={`tel:${propData.numero}`}
								>
									<Phone className="size-4" />
									<span>{propData.numero}</span>
								</a>
								<Link href={`https://wa.me/${propData.numero}`} target="_blank">
									<Button size="sm" variant="success">
										<WhatsAppIcon2 className="size-4 fill-white" />
										WhatsApp
									</Button>
								</Link>
							</div>
						</section>
					)}

					{/* Immobile Section */}
					<section>
						<h3 className="mb-2 font-semibold">{t.contatto.immobile}:</h3>
						<p className="mb-2">
							{t.contatto.indirizzo}: {propData.indirizzo}, {propData.civico}{" "}
							{propData.comune} ({propData.provincia})
						</p>
						{navigationUrl && (
							<Link href={navigationUrl} rel="noreferrer" target="_blank">
								<Button variant="info">
									<Navigation className="size-4" />
									<span>{t.contatto.apri_nav}</span>
								</Button>
							</Link>
						)}
					</section>

					{/* Warning */}
					<div className="flex w-fit items-start gap-3 rounded-md bg-red-500 p-2 text-white">
						<TriangleAlert className="size-6 shrink-0" />
						<div className="space-y-1">
							<p className="font-medium">{t.contatto.contatta}</p>
							<p className="text-sm">{t.contatto.orari}</p>
						</div>
					</div>

					{/* Metadata */}
					<p className="text-muted-foreground text-sm">
						{t.contatto.sbloccato_il}:{" "}
						{opened_at.toLocaleString("it", {
							day: "2-digit",
							month: "2-digit",
							year: "numeric",
							hour: "2-digit",
							minute: "2-digit",
						})}
					</p>
				</div>
			</CredenzaBody>
			<CredenzaFooter>
				<CredenzaClose asChild>
					<Button aria-label="Chiudi modal credenza" variant="outline">
						{t.chiudi}
					</Button>
				</CredenzaClose>
			</CredenzaFooter>
		</>
	);
};
