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>
		);
	}

	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="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 text-primary sm:text-lg">
							<Building className="size-6 fill-background" />
							Affitto {servizio.tipologia}
						</div>
						<div className="float-end flex items-center justify-start pl-2 text-primary">
							{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>
	);
};
