import {
	BedDouble,
	CalendarClock,
	MapPin,
	Maximize2,
	Ruler,
	Siren,
	Star,
	TrafficCone,
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useState } from "react";
import { ImageFlbk } from "~/components/ImageWithFallback";
import {
	Carousel,
	CarouselContent,
	CarouselItem,
	CarouselNext,
	CarouselPrevious,
} from "~/components/ui/carousel";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
} from "~/components/ui/dialog";
import { camereTesti, handleConsegna } from "~/lib/annuncio_details";
import { cn, formatCurrency } from "~/lib/utils";
import { useTranslation } from "~/providers/I18nProvider";
import type { AnnuncioRicerca } from "~/server/controllers/annunci.controller";
import { Badge } from "./ui/badge";
import { VideoPlayer } from "./videoPlayer";

type CardAnnuncioProps = AnnuncioRicerca & {
	className?: string;
};

export const CardAnnuncio = ({
	id,
	codice,
	prezzo,
	titolo_it,
	titolo_en,
	mq,
	comune,
	provincia,
	consegna,
	numero_camere: camere,
	tipo,
	stato,
	className,
	url_video: videos,
	updated_at,
	images,
	homepage,
}: CardAnnuncioProps) => {
	const { t, locale } = useTranslation();
	const currentMonth = new Date().getMonth() + 1;
	const isAvailableNow = consegna === 0 || consegna === currentMonth;

	return (
		<div
			className={cn(
				"h-[31.1rem] rounded-md bg-white shadow-neutral-100 shadow-sm hover:shadow-md hover:outline-neutral-600",
				className,
			)}
			id={`card-annuncio-${id}`}
		>
			<Link
				className="flex h-full flex-col gap-2 p-2"
				href={`/annuncio/${codice}`} //duration-700 ease-in-out animate-in fade-in
			>
				<div
					className={cn("group relative overflow-clip text-clip rounded-md")}
				>
					<div
						className={cn(
							"absolute inset-0 z-20 size-full rounded-md",
							homepage &&
								(isAvailableNow
									? "border-[.35rem] border-green-500"
									: "border-[.35rem] border-blue-500"),

							stato === "Trattativa" && "border-[.35rem] border-violet-500",
						)}
					></div>
					{stato !== "Trattativa" && homepage && (
						<div className="absolute top-1 z-20 flex w-full justify-center px-2">
							<Badge
								className={cn(
									"flex items-center gap-1.5 rounded-t-none px-1 py-0.5 font-semibold text-base text-white shadow-lg [&>svg]:size-4.5",
									isAvailableNow ? "bg-green-500" : "bg-blue-500",
								)}
							>
								{isAvailableNow ? (
									<>
										<span>Disponibile Subito</span>
										<Siren />
									</>
								) : (
									<>
										<span>In Evidenza</span>
										<Star />
									</>
								)}
							</Badge>
						</div>
					)}
					{stato === "Trattativa" && (
						<div className="absolute top-1 z-20 flex w-full justify-center px-2">
							<Badge
								className={cn(
									"flex items-center gap-1.5 rounded-t-none bg-violet-500 px-1 py-0.5 font-semibold text-base text-white shadow-lg [&>svg]:size-4.5",
								)}
							>
								<span>In Trattativa</span>
								<TrafficCone />
							</Badge>
						</div>
					)}

					<Carousel opts={{ loop: true }}>
						<CarouselContent>
							{images?.map((img, idx) => (
								<CarouselItem key={`${img.img}key`}>
									<ImageFlbk
										alt={t.card.alt_immagine}
										blurDataURL={`/storage-api/get/${img.thumb}?image=true`}
										className={"h-64 w-full object-cover"}
										height={1080}
										priority={idx === 0}
										src={`/storage-api/get/${img.img}?image=true`}
										width={1920}
									/>
								</CarouselItem>
							))}
							{videos?.map((video) => {
								if (!video) return null;
								if (video.includes("youtu")) {
									return null;
								}
								return (
									<CarouselItem
										className={cn("group relative")}
										key={`videoplayer-${video}`}
										onClick={(e) => {
											e.preventDefault();
											e.stopPropagation();
										}}
									>
										<VideoPlayer
											cacheKey={updated_at?.toString() || new Date().toString()}
											className="h-56"
											coverImage={
												images?.[0]
													? `/storage-api/get/${images[0].img}?image=true`
													: ""
											}
											key={`videoplayer-${video}`}
											videoSrc={video}
										/>
									</CarouselItem>
								);
							})}
						</CarouselContent>

						<div
							className="block opacity-0 transition-all duration-200 group-hover:opacity-60 disabled:group-hover:opacity-0"
							onClick={(e) => e.preventDefault()}
							onKeyDown={(e) => e.stopPropagation()}
							role="button"
							tabIndex={0}
						>
							<CarouselPrevious
								className="left-2 cursor-pointer"
								disabled={!images || images.length === 1}
							/>
							<CarouselNext
								className="right-2 cursor-pointer"
								disabled={!images || images.length === 1}
							/>
						</div>
					</Carousel>
				</div>
				<div className="flex h-full grow flex-col gap-2">
					<div
						className={cn(
							"flex w-full items-center justify-center rounded-md",
							tipo === "Transitorio" && "bg-transitorio",
							tipo === "Stabile" && "bg-stabile",
							tipo === "Cessione" && "bg-blue-400",
							tipo === "Vendita" && "bg-green-400",
						)}
					>
						<div className="font-semibold text-white">Affitto {tipo}</div>
					</div>
					<div className="flex flex-row justify-between gap-3 px-4">
						<div className="w-full text-center">
							<span className="sr-only">{t.card.codice}</span>

							<span className="font-semibold text-red-500 text-xl">
								Cod: {codice}
							</span>
						</div>
						<div className="w-full text-center">
							<span className="sr-only">{t.card.prezzo}</span>

							<span className="font-semibold text-xl">
								{formatCurrency(prezzo / 1e2)}
							</span>
						</div>
					</div>
					<div className="flex h-full grow flex-col justify-between">
						<div className="px-4 text-center text-muted-foreground">
							<span className="sr-only">{t.card.titolo}</span>

							<span className="line-clamp-3 overflow-ellipsis font-medium text-base">
								{locale === "it" ? titolo_it : titolo_en}
							</span>
						</div>
						<div className="flex flex-col gap-4">
							<div className="text-center text-muted-foreground">
								<span className="sr-only">{t.card.indirizzo}</span>
								<MapPin className="mr-1 mb-1 inline-block size-4" />
								<span className="font-medium text-sm">
									{comune && provincia && `${comune} (${provincia})`}
								</span>
							</div>

							<div className="flex h-9 items-center justify-around gap-1.5 text-neutral-700 text-xs">
								<div className="flex h-full w-full items-center justify-center gap-1 rounded-md bg-neutral-100">
									<Ruler className="size-4 text-neutral-900" />

									<div>
										<p className="font-medium">
											{mq ? Number.parseFloat(mq) : 0}{" "}
											<span>
												m<sup>2</sup>
											</span>
										</p>
									</div>
								</div>
								<div className="flex h-full w-full items-center justify-center gap-1 rounded-md bg-neutral-100">
									<BedDouble className="size-4 text-neutral-900" />

									<div>
										<p className="font-medium">
											{camereTesti({ camere: camere, testi: t.card })}
										</p>
									</div>
								</div>
								<div className="flex h-full w-full items-center justify-center gap-1 rounded-md bg-neutral-100">
									<CalendarClock className="size-4 text-neutral-900" />

									<div>
										<p className="truncate font-medium">
											{handleConsegna({
												aggiornamento: t.card.in_aggiornamento,
												consegna: consegna,
												consegna_da: t.card.consegna_da,
												mesi: t.preferenze.mesi,
												subito: t.card.consegna_subito,
											})}
										</p>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</Link>
		</div>
	);
};

export const CarouselAnnuncio = ({
	single,
	immagini,
	videos,
	updated_at,
}: {
	single?: boolean;
	immagini: string[] | null;
	videos: string[] | null;
	updated_at: Date | null;
}) => {
	const [openModal, setOpenModal] = useState(false);
	const [idxModal, setIdxModal] = useState(0);
	function handleOpenModal(position: number) {
		setIdxModal(position);
		setOpenModal(true);
	}
	return (
		<>
			<div className="mx-auto my-4 w-full text-clip rounded-md">
				<div className="relative">
					<Carousel opts={{ align: "start", loop: true }}>
						<CarouselContent>
							{immagini?.map((img, idx) => (
								<CarouselItem
									className={cn(
										"group relative flex items-center justify-center",
										immagini && immagini.length === 1
											? ""
											: !single && "md:basis-1/2 lg:basis-1/3",
									)}
									key={`${img}-cF`}
								>
									<ImageFlbk
										alt={img}
										className={cn(
											"aspect-square max-h-92 w-full rounded-md object-cover sm:max-h-80 xl:max-h-[25rem]",
											immagini.length === 1 && "object-contain",
										)}
										height={400}
										onClick={() => handleOpenModal(idx)}
										priority={idx === 0}
										src={`/storage-api/get/${img}?image=true&${updated_at?.toString() || new Date().toString()}`}
										width={800}
									/>
									<Maximize2
										className="absolute right-2 bottom-2 size-7 origin-bottom-right cursor-pointer rounded-md bg-white/70 stroke-2 p-1 transition-all duration-300 ease-in-out hover:scale-150 group-hover:opacity-100 sm:opacity-0"
										onClick={() => handleOpenModal(idx)}
									/>
								</CarouselItem>
							))}
							{videos?.map((video, idx) => {
								if (!video) return null;
								if (video.includes("youtu")) {
									return null;
								}
								return (
									<CarouselItem
										className={cn(
											"group relative",
											immagini && immagini.length === 1
												? ""
												: !single && "md:basis-1/2 lg:basis-1/3",
										)}
										key={`videoplayer-${video}`}
									>
										<VideoPlayer
											cacheKey={updated_at?.toString() || new Date().toString()}
											className="h-72"
											coverImage={
												immagini?.[0]
													? `/storage-api/get/${immagini[0]}?image=true`
													: ""
											}
											key={`videoplayer-${idx}-${openModal}`}
											videoSrc={video}
										/>

										<Maximize2
											className="absolute right-2 bottom-2 size-7 origin-bottom-right cursor-pointer rounded-md bg-white/70 stroke-2 p-1 transition-all duration-300 ease-in-out hover:scale-150 group-hover:opacity-100 sm:opacity-0"
											onClick={() =>
												handleOpenModal(immagini?.length || 0 + idx)
											}
										/>
									</CarouselItem>
								);
							})}
						</CarouselContent>

						<CarouselPrevious
							className="left-2 cursor-pointer opacity-60 disabled:opacity-0"
							disabled={!immagini || immagini.length === 1}
							type="button"
						/>
						<CarouselNext
							className="right-2 cursor-pointer opacity-60 disabled:opacity-0"
							disabled={!immagini || immagini.length === 1}
							type="button"
						/>
					</Carousel>
				</div>
			</div>
			<Dialog onOpenChange={setOpenModal} open={openModal}>
				<DialogContent className="flex h-full w-full max-w-full items-center justify-center border-transparent border-none bg-white p-0 md:max-w-[80vw] md:p-6 [&_#dialog-close>svg]:size-8">
					<DialogHeader className="absolute top-0 right-0 left-0 z-10">
						<DialogTitle className="sr-only">Image Dialog</DialogTitle>
						<DialogDescription className="sr-only">Immagine</DialogDescription>
					</DialogHeader>
					<Carousel opts={{ loop: true, startIndex: idxModal }}>
						<CarouselContent>
							{immagini?.map((img, idx) => (
								<CarouselItem key={`${img}-cD`}>
									<Image
										alt={`carousel-img-${idx}`}
										className="mx-auto h-[90vh] w-full rounded-md object-contain sm:w-[80vw]"
										height={1080}
										src={`/storage-api/get/${img}?image=true&${updated_at?.toString() || new Date().toString()}`}
										width={1920}
									/>
								</CarouselItem>
							))}
							{videos?.map((video) => {
								if (!video) return null;
								if (video.includes("youtu")) {
									return null;
								}
								return (
									<CarouselItem
										className="relative flex items-center justify-center"
										key={`carousel-videoplayer-${video}`}
									>
										<VideoPlayer
											cacheKey={updated_at?.toString() || new Date().toString()}
											className="absolute mx-auto h-[90vh] w-full max-w-fit rounded-md object-contain"
											coverImage={
												immagini?.[0]
													? `/storage-api/get/${immagini[0]}?image=true`
													: ""
											}
											videoSrc={video}
										/>
									</CarouselItem>
								);
							})}
						</CarouselContent>

						<CarouselPrevious
							className="left-2 cursor-pointer opacity-60 disabled:opacity-0"
							disabled={!immagini || immagini.length === 1}
							type="button"
						/>
						<CarouselNext
							className="right-2 cursor-pointer opacity-60 disabled:opacity-0"
							disabled={!immagini || immagini.length === 1}
							type="button"
						/>
					</Carousel>
				</DialogContent>
			</Dialog>
		</>
	);
};
