import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { DEDUCTION_PRESETS_CENTS, formatCents } from "@/lib/drinkkaart";
import { orpc } from "@/utils/orpc";

interface DeductionPanelProps {
	drinkkaartId: string;
	userName: string;
	userEmail: string;
	balance: number;
	onSuccess: (transactionId: string, balanceAfter: number) => void;
	onCancel: () => void;
}

export function DeductionPanel({
	drinkkaartId,
	userName,
	balance,
	onSuccess,
	onCancel,
}: DeductionPanelProps) {
	const [selectedCents, setSelectedCents] = useState<number>(200);
	const [customCents, setCustomCents] = useState("");
	const [useCustom, setUseCustom] = useState(false);
	const [note, setNote] = useState("");
	const [confirming, setConfirming] = useState(false);

	const amountCents = useCustom
		? Math.round((Number.parseFloat(customCents || "0") || 0) * 100)
		: selectedCents;

	const isValid =
		Number.isInteger(amountCents) && amountCents >= 1 && amountCents <= balance;

	const deductMutation = useMutation(
		orpc.drinkkaart.deductBalance.mutationOptions(),
	);

	const handleConfirm = () => {
		if (!isValid) return;
		deductMutation.mutate(
			{ drinkkaartId, amountCents, note: note || undefined },
			{
				onSuccess: (data) => {
					onSuccess(data.transactionId, data.balanceAfter);
				},
			},
		);
	};

	if (confirming) {
		return (
			<div className="rounded-xl border border-red-400/20 bg-red-400/5 p-5">
				<p className="mb-2 text-white">
					Bevestig afschrijving van{" "}
					<strong className="text-red-300">{formatCents(amountCents)}</strong>{" "}
					voor <strong>{userName}</strong>
				</p>
				<p className="mb-4 text-sm text-white/50">
					Nieuw saldo: {formatCents(balance - amountCents)}
				</p>
				{deductMutation.isError && (
					<p className="mb-3 text-red-400 text-sm">
						{(deductMutation.error as Error)?.message ??
							"Fout bij afschrijving"}
					</p>
				)}
				<div className="flex gap-3">
					<Button
						onClick={handleConfirm}
						disabled={deductMutation.isPending}
						className="flex-1 bg-red-500 text-white hover:bg-red-600"
					>
						{deductMutation.isPending ? "Verwerken..." : "Bevestigen"}
					</Button>
					<Button
						onClick={() => {
							setConfirming(false);
							deductMutation.reset();
						}}
						variant="outline"
						disabled={deductMutation.isPending}
						className="border-white/20 bg-transparent text-white hover:bg-white/10"
					>
						Terug
					</Button>
				</div>
			</div>
		);
	}

	return (
		<div className="space-y-4">
			{/* Preset amounts */}
			<div>
				<p className="mb-2 text-sm text-white/60">Bedrag</p>
				<div className="grid grid-cols-4 gap-2">
					{DEDUCTION_PRESETS_CENTS.map((cents) => (
						<button
							key={cents}
							type="button"
							onClick={() => {
								setSelectedCents(cents);
								setUseCustom(false);
							}}
							className={`rounded-lg border py-3 font-medium text-sm transition-colors ${
								!useCustom && selectedCents === cents
									? "border-white bg-white text-[#214e51]"
									: "border-white/20 text-white hover:border-white/50"
							}`}
						>
							{formatCents(cents)}
						</button>
					))}
				</div>
			</div>

			{/* Custom amount */}
			<div>
				<label
					htmlFor="deduct-custom"
					className="mb-1 block text-sm text-white/60"
				>
					Eigen bedrag (€)
				</label>
				<div className="relative">
					<span className="absolute top-1/2 left-3 -translate-y-1/2 text-white/50">
						€
					</span>
					<Input
						id="deduct-custom"
						type="number"
						min="0.01"
						step="0.01"
						placeholder="Bijv. 2.50"
						value={customCents}
						onChange={(e) => {
							setCustomCents(e.target.value);
							setUseCustom(true);
						}}
						className="border-white/20 bg-white/10 pl-8 text-white placeholder:text-white/30"
					/>
				</div>
			</div>

			{/* Note */}
			<div>
				<label
					htmlFor="deduct-note"
					className="mb-1 block text-sm text-white/60"
				>
					Opmerking (optioneel)
				</label>
				<Input
					id="deduct-note"
					value={note}
					onChange={(e) => setNote(e.target.value)}
					placeholder="Bijv. 'Wijn'"
					maxLength={200}
					className="border-white/20 bg-white/10 text-white placeholder:text-white/30"
				/>
			</div>

			{/* Insufficient balance warning */}
			{amountCents > balance && (
				<p className="text-red-400 text-sm">
					Onvoldoende saldo. Huidig saldo: {formatCents(balance)}
				</p>
			)}

			<div className="flex gap-3">
				<Button
					onClick={() => setConfirming(true)}
					disabled={!isValid}
					className="flex-1 bg-white font-semibold text-[#214e51] hover:bg-white/90 disabled:opacity-50"
				>
					Afschrijven — {isValid ? formatCents(amountCents) : "—"}
				</Button>
				<Button
					onClick={onCancel}
					variant="outline"
					className="border-white/20 bg-transparent text-white hover:bg-white/10"
				>
					Annuleren
				</Button>
			</div>
		</div>
	);
}
