import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { formatCents } from "@/lib/drinkkaart";
import { orpc } from "@/utils/orpc";

interface TransactionRow {
	id: string;
	amountCents: number;
	userName: string;
}

interface ReverseDialogProps {
	transaction: TransactionRow;
	onClose: () => void;
}

export function ReverseDialog({ transaction, onClose }: ReverseDialogProps) {
	const queryClient = useQueryClient();

	const reverseMutation = useMutation(
		orpc.drinkkaart.reverseTransaction.mutationOptions(),
	);

	const handleConfirm = () => {
		reverseMutation.mutate(
			{ transactionId: transaction.id },
			{
				onSuccess: () => {
					toast.success(
						`${formatCents(transaction.amountCents)} teruggestort aan ${transaction.userName}`,
					);
					queryClient.invalidateQueries({
						queryKey: orpc.drinkkaart.getTransactionLog.key(),
					});
					onClose();
				},
				onError: (err: Error) => {
					toast.error(err.message ?? "Fout bij terugdraaien");
				},
			},
		);
	};

	return (
		<div className="fixed inset-0 z-50 flex items-center justify-center">
			<button
				type="button"
				className="absolute inset-0 bg-black/60"
				aria-label="Sluiten"
				onClick={onClose}
			/>
			<div className="relative z-10 w-full max-w-sm rounded-2xl bg-[#1a3d40] p-6">
				<h3 className="mb-3 font-['Intro',sans-serif] text-white text-xl">
					Transactie terugdraaien
				</h3>
				<p className="mb-1 text-white/80">
					Weet je zeker dat je{" "}
					<strong className="text-white">
						{formatCents(transaction.amountCents)}
					</strong>{" "}
					wil terugdraaien voor{" "}
					<strong className="text-white">{transaction.userName}</strong>?
				</p>
				<p className="mb-5 text-sm text-white/50">
					Dit voegt {formatCents(transaction.amountCents)} terug toe aan het
					saldo.
				</p>

				{reverseMutation.isError && (
					<p className="mb-3 text-red-400 text-sm">
						{(reverseMutation.error as Error)?.message ??
							"Fout bij terugdraaien"}
					</p>
				)}

				<div className="flex gap-3">
					<Button
						onClick={handleConfirm}
						disabled={reverseMutation.isPending}
						className="flex-1 bg-white font-semibold text-[#214e51] hover:bg-white/90"
					>
						{reverseMutation.isPending
							? "Verwerken..."
							: "Terugdraaien bevestigen"}
					</Button>
					<Button
						onClick={onClose}
						variant="outline"
						disabled={reverseMutation.isPending}
						className="border-white/20 bg-transparent text-white hover:bg-white/10"
					>
						Annuleren
					</Button>
				</div>
			</div>
		</div>
	);
}
