import { ChevronDownCircle, ChevronRightCircle, Package } 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>
		);
	}

	const first_choice = data.findIndex((s) => !s.isInterrotto && s.isOkAcconto);
	const second_choice = data.findIndex((s) => !s.isInterrotto);
	const getDefaultOpen = (idx: number) => {
		if (first_choice !== -1) return idx === first_choice;
		if (second_choice !== -1) return idx === second_choice;
		return idx === 0;
	};

	return (
		<div className="flex flex-col gap-8">
			{data.map((servizio, idx) => {
				return (
					<Row
						defaultOpen={getDefaultOpen(idx)}
						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="grid w-full cursor-pointer grid-cols-10 items-center">
						<div className="col-span-2 flex items-center justify-center text-primary sm:col-span-1">
							{isOpen ? (
								<ChevronDownCircle className="fill-background" />
							) : (
								<ChevronRightCircle className="fill-background" />
							)}
						</div>
						<div className="col-span-6 flex items-center gap-2 font-semibold sm:text-lg">
							<Package className="size-6 text-primary" />
							Affitto {servizio.tipologia}
						</div>
						<div className="col-span-2">
							{(() => {
								if (servizio.isInterrotto)
									return <span className="text-red-500">Interrotto</span>;
								if (servizio.isOkAcconto && servizio.decorrenza !== null) {
									return <span className="text-green-500">Attivo</span>;
								}
								return <span className="text-neutral-500">Inattivo</span>;
							})()}
						</div>
						<div className="hidden text-sm sm:col-span-2 sm:contents sm:text-base">
							{servizio.created_at.toLocaleDateString("it", {
								day: "2-digit",
								month: "short",
							})}
						</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>
	);
};
