import { FolderKanban, ShieldUser, Trash2, Wrench } from "lucide-react";
import Link from "next/link";
import toast from "react-hot-toast";
import { Confirm } from "~/components/confirm";
import { Button } from "~/components/ui/button";
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from "~/components/ui/popover";
import { useServizio, useServizioAnnuncio } from "~/providers/ServizioProvider";
import { api } from "~/utils/api";
import { AdminLavoraConferma } from "./admin_conferma";
import { AdminContratto } from "./admin_contratto";

export const AnnuncioActions = () => {
	const { servizioId, userId, isAdmin } = useServizio();
	const { data, annuncioId } = useServizioAnnuncio();

	const utils = api.useUtils();
	const { mutate } = api.servizio.removeAnnuncioServizio.useMutation({
		onError: (error) => {
			console.error(error);
			toast.error("Errore durante la rimozione dell'annuncio");
		},
		onSuccess: async () => {
			await utils.servizio.getAllServizioAnnunci.invalidate({ userId });
			await utils.servizio.getCompatibileAnnunci.invalidate({
				servizioId,
			});
			toast.success("Annuncio rimosso");
		},
	});

	if ((!isAdmin && data.open_contatti_at == null) || isAdmin) {
		return (
			<div className="flex w-full max-w-fit flex-wrap justify-start gap-3 sm:justify-end">
				{isAdmin && data.user_confirmed_at != null && <AdminLavoraConferma />}
				{isAdmin && data.accettato_conferma_at != null && (
					<>
						<AdminContratto />
						{data.gestionale_id && (
							<Link
								aria-label="Open Gestionale"
								href={`https://win-jk822fggr6b:480/id/${data.gestionale_id}`}
								target="_blank"
							>
								<Button>
									<FolderKanban className="size-5" /> Gestionale
								</Button>
							</Link>
						)}
					</>
				)}
				{isAdmin && (
					<Popover>
						<PopoverTrigger asChild>
							<Button>
								<ShieldUser />
								<span>Admin</span>
							</Button>
						</PopoverTrigger>
						<PopoverContent
							align="end"
							className="flex w-fit flex-col items-center gap-4"
						>
							<Link
								href={`/area-riservata/admin/edit-annuncio/${annuncioId}`}
								target="_blank"
							>
								<Button
									aria-label="Edit Annuncio"
									className="w-full"
									size="sm"
									variant="secondary"
								>
									<Wrench />
									<span>Modifica Annuncio</span>
								</Button>
							</Link>

							<Confirm
								description="Sei sicuro di voler eliminare l'annuncio?"
								onConfirm={() => {
									mutate({
										annuncioId,
										servizioId,
									});
								}}
								title="Elimina annuncio"
							>
								<Button
									aria-label="Delete Annuncio"
									className="w-full"
									size="sm"
									variant="destructive"
								>
									<Trash2 />
									<span>Elimina Annuncio</span>
								</Button>
							</Confirm>
						</PopoverContent>
					</Popover>
				)}
			</div>
		);
	}
	return null;
};
