import { add } from "date-fns";
import { Building, ChevronDown, ChevronUp } from "lucide-react";
import { useState } from "react";
import { LoadingPage } from "~/components/loading";
import { ServizioContent } from "~/components/servizio/main";
import {
	Collapsible,
	CollapsibleContent,
	CollapsibleTrigger,
} from "~/components/ui/collapsible";
import { cn } from "~/lib/utils";
import { ServizioProvider } from "~/providers/ServizioProvider";
import type { UsersId } from "~/schemas/public/Users";
import type { ServizioData } from "~/server/controllers/servizio.controller";
import { api } from "~/utils/api";

export const TabRicerca = ({
	userId,
	isAdmin,
}: {
	userId: UsersId;
	isAdmin: boolean;
}) => {
	const { data, isLoading } = api.servizio.getAllServizioAnnunci.useQuery({
		userId,
	});

	if (isLoading) return <LoadingPage />;
	if (!data || data.length === 0) {
		return (
			<div className="m-4 rounded-md bg-yellow-100 p-4 text-yellow-900">
				Nessun servizio attualmente inserito
			</div>
		);
	}

	return (
		<div className="flex flex-col gap-8">
			{data.map((servizio) => {
				return (
					<Row
						defaultOpen={
							!servizio.isInterrotto ||
							new Date() < add(servizio.created_at, { days: 60 })
						}
						isAdmin={isAdmin}
						key={servizio.servizio_id}
						servizio={servizio}
						userId={userId}
					/>
				);
			})}
		</div>
	);
};

const Row = ({
	servizio,
	userId,
	isAdmin,
	defaultOpen = false,
}: {
	servizio: ServizioData;
	userId: UsersId;
	isAdmin: boolean;
	defaultOpen: boolean;
}) => {
	const [isOpen, setIsOpen] = useState(defaultOpen);
	return (
		<ServizioProvider
			isAdmin={isAdmin}
			servizio={servizio}
			servizioId={servizio.servizio_id}
			userId={userId}
		>
			<Collapsible onOpenChange={setIsOpen} open={isOpen}>
				<div
					className={cn(
						"flex items-center rounded-md border border-primary bg-secondary py-2 shadow-sm hover:shadow-md",
						isOpen && "rounded-b-none",
					)}
				>
					<CollapsibleTrigger className="flex w-full cursor-pointer items-center justify-between gap-4 px-3 sm:px-4">
						<div className="flex items-center gap-2 font-semibold">
							<Building className="size-6 stroke-foreground" />

							<span className="sm:text-lg">Affitto {servizio.tipologia}</span>
							<span className="text-muted-foreground text-xs sm:text-sm">
								{`${servizio.created_at.toLocaleDateString("it")}`}
							</span>
						</div>
						<div className="float-end flex items-center justify-start pl-2">
							{isOpen ? <ChevronUp /> : <ChevronDown />}
						</div>
					</CollapsibleTrigger>
				</div>

				<CollapsibleContent className="mt-0 overflow-hidden transition-all duration-300 ease-in-out data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">
					<ServizioContent />
				</CollapsibleContent>
			</Collapsible>
		</ServizioProvider>
	);
};
