import { ExternalLink, UnfoldVertical } from "lucide-react";
import Link from "next/link";
import {
	Credenza,
	CredenzaBody,
	CredenzaClose,
	CredenzaContent,
	CredenzaDescription,
	CredenzaFooter,
	CredenzaHeader,
	CredenzaTitle,
	CredenzaTrigger,
} from "~/components/custom_ui/credenza";
import { ImageFlbk } from "~/components/ImageWithFallback";
import { AnnuncioActions } from "~/components/servizio/annuncio_actions";
import { Interactions } from "~/components/servizio/interactions";
import { Button } from "~/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
import {
	Carousel,
	CarouselContent,
	CarouselItem,
	CarouselNext,
	CarouselPrevious,
} from "~/components/ui/carousel";
import { handleConsegna } from "~/lib/annuncio_details";
import { replaceWithBr } from "~/lib/newlineToBr";
import { cn, formatCurrency } from "~/lib/utils";
import { useTranslation } from "~/providers/I18nProvider";
import { useServizioAnnuncio } from "~/providers/ServizioProvider";
import type { Annunci } from "~/schemas/public/Annunci";
import { CacheKey } from "~/utils/imageCache";

export const AnnuncioCard = ({ className }: { className?: string }) => {
	const { data } = useServizioAnnuncio();

	return (
		<BasicAnnuncioCard
			actions={<AnnuncioActions />}
			className={className}
			data={data}
			interactions={<Interactions />}
		/>
	);
};
export const BasicAnnuncioCard = ({
	actions,
	interactions,
	className,
	data,
}: {
	actions?: React.ReactNode;
	interactions?: React.ReactNode;
	className?: string;
	data: Pick<
		Annunci,
		| "id"
		| "codice"
		| "prezzo"
		| "desc_en"
		| "desc_it"
		| "url_immagini"
		| "titolo_en"
		| "titolo_it"
		| "tipo"
		| "consegna"
		| "stato"
		| "web"
	>;
}) => {
	const { t } = useTranslation();

	return (
		<Card className={cn("w-full border-white py-5", className)}>
			<CardHeader className="flex flex-row flex-wrap items-center justify-between space-y-0 pb-0">
				<CardTitle className="text-2xl">Codice: {data.codice}</CardTitle>
				{actions}
			</CardHeader>
			<CardContent className="px-4">
				<div className="flex w-full flex-col gap-4 md:flex-row md:gap-10">
					<ImageFlbk
						alt={data.codice}
						className="h-auto max-h-72 w-full rounded-md object-contain sm:max-w-xs"
						height={1080}
						priority
						src={
							(data.url_immagini &&
								`/go-api/images/get/${data.url_immagini[0]}?${CacheKey}`) ||
							"/fallback-image.png"
						}
						width={1920}
					/>
					<div className="flex w-full flex-col gap-5">
						{interactions}

						<div className="flex flex-wrap items-center gap-3">
							<TipoBadge tipo={data.tipo} />
							<span>
								{handleConsegna({
									aggiornamento: t.card.in_aggiornamento,
									consegna: data.consegna,
									consegna_da: t.card.consegna_da,
									mesi: t.preferenze.mesi,
									subito: t.card.consegna_subito,
								})}
							</span>
							<span>{formatCurrency(data.prezzo / 1e2)}</span>
						</div>
						<div className="flex w-full flex-wrap items-center gap-5">
							<span className="text-wrap">{data.titolo_it || data.codice}</span>
							<div className="flex flex-wrap items-center gap-2">
								<AnnuncioDettaglio data={data} />
								{data.stato !== "Sospeso" && data.web && (
									<Link
										aria-label="Pagina Annuncio"
										href={`/annuncio/${data.codice}`}
									>
										<Button
											className="flex items-center gap-2"
											variant="outline"
										>
											<ExternalLink className="size-6" />
										</Button>
									</Link>
								)}
							</div>
						</div>
					</div>
				</div>
			</CardContent>
		</Card>
	);
};

const TipoBadge = ({ tipo }: { tipo: Annunci["tipo"] }) => {
	return (
		<div
			className={cn(
				"flex w-fit items-center justify-center rounded-md px-3",
				tipo === "Transitorio" && "bg-orange-400",
				tipo === "Stabile" && "bg-red-400",
				tipo === "Cessione" && "bg-blue-400",
				tipo === "Vendita" && "bg-green-400",
			)}
		>
			<div className="font-semibold text-white">{tipo}</div>
		</div>
	);
};

const AnnuncioDettaglio = ({
	data,
}: {
	data: Pick<
		Annunci,
		| "id"
		| "codice"
		| "prezzo"
		| "desc_en"
		| "desc_it"
		| "url_immagini"
		| "titolo_en"
		| "titolo_it"
		| "tipo"
		| "consegna"
		| "stato"
		| "web"
	>;
}) => {
	const { locale, t } = useTranslation();

	return (
		<Credenza>
			<CredenzaTrigger asChild>
				<Button
					aria-label="Dettagli Annuncio"
					className="flex items-center gap-2"
					variant="outline"
				>
					<UnfoldVertical className="size-6" /> Dettagli annuncio
				</Button>
			</CredenzaTrigger>
			<CredenzaContent className="max-h-[90vh] md:max-w-6xl">
				<CredenzaHeader>
					<CredenzaTitle className="text-xl">
						Annuncio {data.codice}
					</CredenzaTitle>
					<CredenzaDescription className="sr-only">
						Annuncio {data.codice}
					</CredenzaDescription>
				</CredenzaHeader>
				<CredenzaBody className="scrollbar-default max-h-[80vh] overflow-y-auto pb-5">
					<div className="flex flex-col gap-2 px-2">
						<Carousel opts={{ loop: true }}>
							<CarouselContent>
								{data?.url_immagini?.map((img, idx) => (
									<CarouselItem key={img}>
										<ImageFlbk
											alt={`${data.codice} - ${idx}`}
											className={"h-80 w-full object-contain sm:h-[35rem]"}
											height={200}
											priority={idx === 0}
											src={`/go-api/images/get/${img}?${CacheKey}`}
											width={400}
										/>
									</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={
										!data.url_immagini || data.url_immagini.length === 1
									}
								/>
								<CarouselNext
									className="right-2 cursor-pointer"
									disabled={
										!data.url_immagini || data.url_immagini.length === 1
									}
								/>
							</div>
						</Carousel>
						<div>
							<TipoBadge tipo={data.tipo} />

							<div className="mt-1 space-y-2">
								<div className="flex flex-row justify-around">
									<div className="text-center">
										<dt className="sr-only">{t.card.codice}</dt>

										<dd className="font-semibold text-lg">
											Cod: {data.codice}
										</dd>
									</div>
									<div className="text-center">
										<dt className="sr-only">{t.card.prezzo}</dt>

										<dd className="font-semibold text-lg">
											{formatCurrency(data.prezzo / 1e2)}
										</dd>
									</div>
								</div>

								<div className="mb-3">
									<dt className="sr-only">{t.card.titolo}</dt>

									<dd className="font-semibold text-base md:text-lg">
										{locale === "it" ? data.titolo_it : data.titolo_en}
									</dd>
								</div>

								<div className="mb-3">
									<dd
										className="text-base"
										dangerouslySetInnerHTML={{
											__html: replaceWithBr(
												(locale === "it" ? data.desc_it : data.desc_en) || "",
											),
										}}
									/>
								</div>
							</div>
						</div>
					</div>
				</CredenzaBody>
				<CredenzaFooter>
					<CredenzaClose asChild>
						<Button aria-label="Chiudi Credenza">Chiudi</Button>
					</CredenzaClose>
				</CredenzaFooter>
			</CredenzaContent>
		</Credenza>
	);
};
