import {
	Copy,
	EllipsisVertical,
	ExternalLink,
	Trash2,
	Wrench,
} from "lucide-react";
import Link from "next/link";
import toast from "react-hot-toast";
import { LoadingPage } from "~/components/loading";
import { AddAnnuncio } from "~/components/servizio/servizio_actions";
import { Button } from "~/components/ui/button";
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuPortal,
	DropdownMenuRadioGroup,
	DropdownMenuRadioItem,
	DropdownMenuSeparator,
	DropdownMenuSub,
	DropdownMenuSubContent,
	DropdownMenuSubTrigger,
	DropdownMenuTrigger,
} from "~/components/ui/dropdown-menu";
import {
	Table,
	TableBody,
	TableCaption,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "~/components/ui/table";
import {
	Tooltip,
	TooltipContent,
	TooltipTrigger,
} from "~/components/ui/tooltip";
import { env } from "~/env";
import type { AnnunciId } from "~/schemas/public/Annunci";
import type { Servizio, ServizioServizioId } from "~/schemas/public/Servizio";
import type { UsersId } from "~/schemas/public/Users";
import { api } from "~/utils/api";

export const TabServizio = ({
	userId,
	setEditData,
	setOpen,
}: {
	userId: UsersId;
	setEditData: (data: Servizio | undefined) => void;
	setOpen: (open: boolean) => void;
}) => {
	const { data } = api.servizio.getUserServizi.useQuery({ userId });
	const utils = api.useUtils();
	const { mutate: remove } = api.servizio.deleteServizio.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success("Servizio rimosso con successo");
			await utils.servizio.getUserServizi.invalidate();
		},
	});

	const { mutate: update } = api.servizio.updateServizio.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async (data) => {
			toast.success("Servizio modificato con successo");
			await utils.servizio.getUserServizi.invalidate();
			await utils.servizio.getPacksSolution.invalidate({
				servizioId: data.servizio_id,
			});
		},
	});

	if (!data) return <LoadingPage />;
	return (
		<Table>
			<TableCaption>
				{data.length > 0
					? "Lista dai servizi dell'utente"
					: "Nessun servizio attualmente inserito"}
			</TableCaption>
			<TableHeader>
				<TableRow>
					<TableHead>Id</TableHead>
					<TableHead>Tipologia</TableHead>
					<TableHead>Creato Il</TableHead>
					<TableHead>Inviato</TableHead>
					<TableHead>Status</TableHead>
					<TableHead></TableHead>
					<TableHead></TableHead>
				</TableRow>
			</TableHeader>
			<TableBody>
				{data.map((servizio) => {
					const onboardDone =
						servizio.isInterrotto ||
						servizio.isOkAcconto ||
						servizio.decorrenza !== null;
					return (
						<TableRow key={servizio.servizio_id}>
							<TableCell className="max-w-20 truncate font-medium">
								{servizio.servizio_id}
							</TableCell>
							<TableCell>{servizio.tipologia}</TableCell>
							<TableCell>
								{new Date(servizio.created_at).toLocaleDateString("it-IT", {
									day: "2-digit",
									month: "2-digit",
									year: "numeric",
								})}
							</TableCell>
							<TableCell>
								{servizio.isSent ? (
									<span className="text-green-500">Inviato</span>
								) : (
									<span className="text-neutral-500">Non inviato</span>
								)}
							</TableCell>
							<TableCell>
								{(() => {
									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>;
								})()}
							</TableCell>
							<TableCell>
								<AnnunciSection
									selectedAnnunci={servizio.annunci}
									servizioId={servizio.servizio_id}
									userId={userId}
								/>
							</TableCell>
							<TableCell>
								<DropdownMenu>
									<DropdownMenuTrigger asChild>
										<Button aria-label="Servizio Actions" variant="outline">
											<EllipsisVertical />
										</Button>
									</DropdownMenuTrigger>
									<DropdownMenuContent>
										<DropdownMenuItem asChild>
											<Link
												aria-label="Apri Onboarding Servizio"
												className="!p-0"
												href={`/area-riservata/admin/user-view/onboard/${servizio.servizio_id}`}
											>
												<Button
													className="flex w-full justify-start gap-3 px-2 font-normal"
													disabled={onboardDone}
													size="sm"
													variant="ghost"
												>
													<ExternalLink className="size-5 stroke-foreground" />
													Apri Onboarding
												</Button>
											</Link>
										</DropdownMenuItem>
										<DropdownMenuItem asChild>
											<Button
												aria-label="Invia Email Servizio"
												className="flex w-full justify-start gap-3 px-2 font-normal"
												disabled={onboardDone}
												onClick={async () => {
													await navigator.clipboard.writeText(
														`${env.NEXT_PUBLIC_BASE_URL}/servizio/pre-onboard/${servizio.servizio_id}`,
													);
													toast.success("Copiato negli appunti", {
														icon: "📋",
													});
												}}
												size="sm"
												variant="ghost"
											>
												<Copy className="size-5 stroke-foreground" />
												Copia Link
											</Button>
										</DropdownMenuItem>
										<DropdownMenuSeparator />
										<DropdownMenuSub>
											<DropdownMenuSubTrigger className="flex items-center gap-3 hover:cursor-pointer">
												<Wrench className="size-5 stroke-foreground" />
												<span className="text-foreground">Status Servizio</span>
											</DropdownMenuSubTrigger>
											<DropdownMenuPortal>
												<DropdownMenuSubContent>
													<DropdownMenuRadioGroup
														onValueChange={(v) => {
															console.log(v);

															update({
																data: {
																	decorrenza: v === "true" ? new Date() : null,
																	isOkAcconto: v === "true",
																},
																servizioId: servizio.servizio_id,
															});
														}}
														value={String(servizio.isOkAcconto)}
													>
														<DropdownMenuRadioItem value="true">
															Attivo
														</DropdownMenuRadioItem>
														<DropdownMenuRadioItem value="false">
															Disattiva
														</DropdownMenuRadioItem>
													</DropdownMenuRadioGroup>
												</DropdownMenuSubContent>
											</DropdownMenuPortal>
										</DropdownMenuSub>
										<DropdownMenuSub>
											<DropdownMenuSubTrigger className="flex items-center gap-3 hover:cursor-pointer">
												<Wrench className="size-5 stroke-foreground" />
												<span className="text-foreground">Interruzione</span>
											</DropdownMenuSubTrigger>
											<DropdownMenuPortal>
												<DropdownMenuSubContent>
													<DropdownMenuRadioGroup
														onValueChange={(v) => {
															update({
																data: {
																	isInterrotto: v === "true",
																},
																servizioId: servizio.servizio_id,
															});
														}}
														value={servizio.isInterrotto.toString()}
													>
														<DropdownMenuRadioItem value="true">
															Interrotto
														</DropdownMenuRadioItem>
														<DropdownMenuRadioItem value="false">
															Non Interrotto
														</DropdownMenuRadioItem>
													</DropdownMenuRadioGroup>
												</DropdownMenuSubContent>
											</DropdownMenuPortal>
										</DropdownMenuSub>

										<DropdownMenuSeparator />
										<DropdownMenuItem
											aria-label="Modifica Parametri Servizio"
											className="flex items-center gap-3 hover:cursor-pointer"
											onClick={() => {
												setEditData(servizio);
												setOpen(true);
											}}
										>
											<Wrench className="size-5 stroke-foreground" />
											Modifica parametri
										</DropdownMenuItem>
										<DropdownMenuItem
											aria-label="Elimina Servizio"
											className="flex items-center gap-3 hover:cursor-pointer"
											onClick={() =>
												confirm("Sei sicuro di voler eliminare il servizio?") &&
												remove({ servizioId: servizio.servizio_id })
											}
										>
											<Trash2 className="size-5 stroke-foreground" />
											Elimina Servizio
										</DropdownMenuItem>
									</DropdownMenuContent>
								</DropdownMenu>
							</TableCell>
						</TableRow>
					);
				})}
			</TableBody>
		</Table>
	);
};

const AnnunciSection = ({
	selectedAnnunci,
	servizioId,
	userId,
}: {
	selectedAnnunci: { codice: string; annunci_id: AnnunciId }[];
	servizioId: ServizioServizioId;
	userId: UsersId;
}) => {
	return (
		<div className="flex items-center gap-3">
			<Tooltip>
				<TooltipTrigger className="w-5">
					{selectedAnnunci?.length}
				</TooltipTrigger>
				<TooltipContent>
					{selectedAnnunci?.length > 0 ? (
						<ul>
							{selectedAnnunci?.map((annuncio) => (
								<li key={annuncio.annunci_id}>{annuncio.codice}</li>
							))}
						</ul>
					) : (
						<span>Nessun annuncio associato</span>
					)}
				</TooltipContent>
			</Tooltip>
			<AddAnnuncio servizioId={servizioId} userId={userId} />
		</div>
	);
};
