import { Info, Toolbox } from "lucide-react";
import Image from "next/image";
import {
	AdminActions,
	UserActions,
} from "~/components/servizio/annuncio_actions";
import {
	AlertDialog,
	AlertDialogCancel,
	AlertDialogContent,
	AlertDialogDescription,
	AlertDialogFooter,
	AlertDialogHeader,
	AlertDialogTitle,
	AlertDialogTrigger,
} from "~/components/ui/alert-dialog";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
import { handleConsegna } from "~/lib/annuncio_details";
import { getStorageUrl } from "~/lib/storage_utils";
import { cn, formatCurrency } from "~/lib/utils";
import { useTranslation } from "~/providers/I18nProvider";
import { useServizio, useServizioAnnuncio } from "~/providers/ServizioProvider";
import type { AnnuncioRicerca } from "~/server/controllers/annunci.controller";
import { api } from "~/utils/api";
import { Button } from "../ui/button";
import {
	Collapsible,
	CollapsibleContent,
	CollapsibleTrigger,
} from "../ui/collapsible";
import { AnnuncioDettaglio, TipoBadge } from "./annuncio_dettaglio";

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

	return (
		<BasicAnnuncioCard
			className={className}
			data={{
				...data,
				modificato_il: data.modificato_il ? new Date(data.modificato_il) : null,
				media_updated_at: data.media_updated_at
					? new Date(data.media_updated_at)
					: null,
			}}
			interactions={
				isAdmin ? (
					<div className="flex flex-col gap-2">
						<Collapsible className="space-y-2">
							<CollapsibleTrigger asChild>
								<Button variant="outline">
									<Toolbox />
									<span>Azioni Utente</span>
								</Button>
							</CollapsibleTrigger>
							<CollapsibleContent className="rounded-md border border-card bg-card p-2">
								<UserActions />
							</CollapsibleContent>
						</Collapsible>

						<AdminActions />
					</div>
				) : (
					<UserActions />
				)
			}
		/>
	);
};

export const BasicAnnuncioCard = ({
	interactions,
	className,
	data,
}: {
	interactions?: React.ReactNode;
	className?: string;
	data: AnnuncioRicerca;
}) => {
	return (
		<Card
			className={cn(
				"w-full max-w-4xl gap-2 rounded-md border-none bg-muted py-3",
				className,
			)}
		>
			<CardHeader className="flex flex-row flex-wrap items-center justify-between space-y-0 px-3 pb-2">
				<CardTitle className="text-2xl">Annuncio {data.codice}</CardTitle>
			</CardHeader>
			<CardContent className="px-3">
				<div
					className={cn("@container flex w-full flex-col gap-4")}
					id="container"
				>
					<AnnuncioDisplay data={data} />
					<div className="flex w-full flex-col gap-4">{interactions}</div>
				</div>
			</CardContent>
		</Card>
	);
};

export const AnnuncioDisplay = ({
	data,
	className,
}: {
	data: AnnuncioRicerca;
	className?: string;
}) => {
	const { isAdmin } = useServizio();
	const { t } = useTranslation();

	return (
		<div
			className={cn(
				"grid @md:grid-cols-[12rem_1fr] grid-cols-[7rem_1fr] @sm:gap-x-4 gap-x-1 gap-y-2 rounded-md bg-card md:max-w-3xl lg:gap-x-4 xl:gap-x-6",
				className,
			)}
		>
			<div className="row-span-1 md:row-span-3">
				<Image
					alt={data.codice}
					className="size-24 rounded-md bg-[#e6e9ec] object-cover md:size-48"
					height={1080}
					priority
					src={
						(data?.images[0] &&
							getStorageUrl({
								storageId: data.images[0].img,
								params: {
									cacheKey: data.media_updated_at?.toISOString(),
									media: "image",
								},
							})) ||
						"/fallback-image.png"
					}
					width={1920}
				/>
			</div>

			<div className="col-span-1 flex w-full max-w-xl flex-wrap gap-5 pt-2 md:col-span-1 md:mt-4 md:pr-8">
				<span className="text-wrap">{data.titolo_it}</span>
			</div>

			<div className="col-span-2 flex w-full max-w-xl items-center justify-between gap-2 md:col-span-1 md:pr-8">
				<TipoBadge mini tipo={data.tipo} />
				<span className="max-w-auto truncate">
					{handleConsegna({
						aggiornamento: t.card.in_aggiornamento,
						consegna: data.consegna,
						consegna_da: t.card.consegna_da,
						mesi: t.parametri.mesi,
						subito: t.card.consegna_subito,
					})}
				</span>
				<span className="font-semibold">
					{formatCurrency(data.prezzo / 1e2)}
				</span>
			</div>
			<div
				className={cn(
					"col-span-2 grid w-full max-w-xl items-center gap-2 md:col-span-1 md:pr-8",
					isAdmin && "grid-cols-2",
				)}
			>
				<AnnuncioDettaglio data={data} />
				{isAdmin && <AdminAnnuncioContatti />}
			</div>
		</div>
	);
};

const AdminAnnuncioContatti = () => {
	const { data } = useServizioAnnuncio();
	const { data: annuncio, isLoading } = api.annunci.getAnnuncioFull.useQuery({
		id: data.id,
	});
	return (
		<AlertDialog>
			<AlertDialogTrigger asChild>
				<Button className="" variant="outline">
					<Info />
					<span>Dati Contatto</span>
				</Button>
			</AlertDialogTrigger>
			<AlertDialogContent>
				<AlertDialogHeader>
					<AlertDialogTitle>Contatti Annuncio {data.codice}</AlertDialogTitle>
					<AlertDialogDescription className="sr-only">
						desc
					</AlertDialogDescription>
				</AlertDialogHeader>
				<div className="flex w-full flex-col gap-4">
					<div>
						<span className="font-semibold">Contatti Aperti il: </span>
						{data.open_contatti_at
							? new Date(data.open_contatti_at).toLocaleString("it-IT")
							: "Non ancora aperti"}
					</div>
					{isLoading ? (
						<div className="flex h-24 w-full items-center justify-center">
							Loading...
						</div>
					) : (
						<>
							<div>
								<span className="font-semibold">Locatore/Incaricato: </span>
								{annuncio?.locatore || "N/A"}
							</div>
							<div>
								<span className="font-semibold">Email: </span>
								{annuncio?.email || "N/A"}
							</div>
							<div>
								<span className="font-semibold">Telefono: </span>
								{annuncio?.numero || "N/A"}
							</div>
						</>
					)}
				</div>
				<AlertDialogFooter>
					<AlertDialogCancel>Chiudi</AlertDialogCancel>
				</AlertDialogFooter>
			</AlertDialogContent>
		</AlertDialog>
	);
};
