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

interface ManualCreditFormProps {
	onDone: () => void;
}

export function ManualCreditForm({ onDone }: ManualCreditFormProps) {
	const [query, setQuery] = useState("");
	const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
	const [selectedUserName, setSelectedUserName] = useState("");
	const [amountEuros, setAmountEuros] = useState("");
	const [reason, setReason] = useState("");

	const searchQuery = useQuery({
		...orpc.drinkkaart.searchUsers.queryOptions({ input: { query } }),
		enabled: query.length >= 2,
	});

	const getDrinkkaartQuery = useQuery({
		...orpc.drinkkaart.getDrinkkaartByUserId.queryOptions({
			input: { userId: selectedUserId ?? "" },
		}),
		enabled: !!selectedUserId,
	});

	const creditMutation = useMutation(
		orpc.drinkkaart.adminCreditBalance.mutationOptions(),
	);

	const amountCents = Math.round(
		(Number.parseFloat(amountEuros || "0") || 0) * 100,
	);
	const isValid =
		selectedUserId &&
		getDrinkkaartQuery.data &&
		amountCents >= 1 &&
		reason.trim().length >= 1;

	const handleSubmit = () => {
		if (!isValid || !getDrinkkaartQuery.data) return;
		creditMutation.mutate(
			{
				drinkkaartId: getDrinkkaartQuery.data.drinkkaartId,
				amountCents,
				reason: reason.trim(),
			},
			{
				onSuccess: () => {
					toast.success(
						`${formatCents(amountCents)} opgeladen voor ${selectedUserName}`,
					);
					onDone();
				},
				onError: (err: Error) => {
					toast.error(err.message ?? "Fout bij opladen");
				},
			},
		);
	};

	return (
		<div className="space-y-4">
			<h3 className="font-['Intro',sans-serif] text-lg text-white">
				Handmatig opladen
			</h3>

			{/* User search */}
			<div>
				<label
					htmlFor="user-search"
					className="mb-1 block text-sm text-white/60"
				>
					Gebruiker zoeken (naam of email)
				</label>
				<Input
					id="user-search"
					value={selectedUserId ? selectedUserName : query}
					onChange={(e) => {
						setQuery(e.target.value);
						setSelectedUserId(null);
					}}
					placeholder="Naam of email..."
					className="border-white/20 bg-white/10 text-white placeholder:text-white/30"
				/>
				{!selectedUserId && query.length >= 2 && searchQuery.data && (
					<ul className="mt-1 rounded-lg border border-white/10 bg-[#1a3d40]">
						{searchQuery.data.length === 0 ? (
							<li className="px-4 py-2 text-sm text-white/40">
								Geen gebruikers gevonden
							</li>
						) : (
							searchQuery.data.map((u) => (
								<li key={u.id}>
									<button
										type="button"
										className="w-full px-4 py-2 text-left text-sm text-white hover:bg-white/10"
										onClick={() => {
											setSelectedUserId(u.id);
											setSelectedUserName(u.name);
											setQuery("");
										}}
									>
										<span className="font-medium">{u.name}</span>
										<span className="ml-2 text-white/50">{u.email}</span>
									</button>
								</li>
							))
						)}
					</ul>
				)}
				{selectedUserId && getDrinkkaartQuery.data && (
					<p className="mt-1 text-sm text-white/50">
						Huidig saldo: {formatCents(getDrinkkaartQuery.data.balance)}
						{" · "}
						<button
							type="button"
							className="text-white/60 underline"
							onClick={() => {
								setSelectedUserId(null);
								setSelectedUserName("");
							}}
						>
							Wijzigen
						</button>
					</p>
				)}
			</div>

			{/* Amount */}
			<div>
				<label
					htmlFor="credit-amount"
					className="mb-1 block text-sm text-white/60"
				>
					Bedrag (€)
				</label>
				<div className="relative">
					<span className="absolute top-1/2 left-3 -translate-y-1/2 text-white/50">
						€
					</span>
					<Input
						id="credit-amount"
						type="number"
						min="0.01"
						step="0.01"
						placeholder="Bijv. 10"
						value={amountEuros}
						onChange={(e) => setAmountEuros(e.target.value)}
						className="border-white/20 bg-white/10 pl-8 text-white placeholder:text-white/30"
					/>
				</div>
			</div>

			{/* Reason */}
			<div>
				<label
					htmlFor="credit-reason"
					className="mb-1 block text-sm text-white/60"
				>
					Reden (verplicht)
				</label>
				<Input
					id="credit-reason"
					value={reason}
					onChange={(e) => setReason(e.target.value)}
					placeholder="Bijv. 'Cash betaling', 'Gift', 'Terugbetaling'"
					maxLength={200}
					className="border-white/20 bg-white/10 text-white placeholder:text-white/30"
				/>
			</div>

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

			<div className="flex gap-3">
				<Button
					onClick={handleSubmit}
					disabled={!isValid || creditMutation.isPending}
					className="flex-1 bg-white font-semibold text-[#214e51] hover:bg-white/90 disabled:opacity-50"
				>
					{creditMutation.isPending
						? "Verwerken..."
						: `Opladen — ${amountCents >= 1 ? formatCents(amountCents) : "—"}`}
				</Button>
				<Button
					onClick={onDone}
					variant="outline"
					className="border-white/20 bg-transparent text-white hover:bg-white/10"
				>
					Annuleren
				</Button>
			</div>
		</div>
	);
}
