"use client";
import { useAtom } from "jotai";
import { CircleDollarSign, Loader2, Wallet2 } from "lucide-react";
import { usePathname, useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { createTopup } from "@/actions/payment";
import { Button } from "@/components/ui/button";
import {
	Drawer,
	DrawerClose,
	DrawerContent,
	DrawerDescription,
	DrawerFooter,
	DrawerHeader,
	DrawerTitle,
	DrawerTrigger,
} from "@/components/ui/drawer";
import { WalletDrawerOpenAtom, walletTopUpValue } from "@/lib/atoms";
import type { TopupType } from "@/lib/types";
import NumberInput from "./number-input";

export function Wallet({ walletBalance }: { walletBalance: number }) {
	const pathname = usePathname();
	const [amount, setAmount] = useAtom(walletTopUpValue);
	const [isOpen, setIsOpen] = useAtom(WalletDrawerOpenAtom);
	const [disabled, setDisabled] = useState(false);
	const router = useRouter();

	if (pathname === "/payment") {
		return null;
	}

	const data: TopupType = {
		amount: Number.parseFloat(amount.toFixed(2)),
	};

	return (
		<Drawer open={isOpen} onOpenChange={setIsOpen}>
			<DrawerTrigger asChild>
				<Button onClick={() => setIsOpen(!isOpen)} variant="outline">
					{walletBalance} MVR
					<Wallet2 />
				</Button>
			</DrawerTrigger>
			<DrawerContent>
				<div className="mx-auto w-full max-w-sm">
					<DrawerHeader>
						<DrawerTitle>Wallet</DrawerTitle>
						<DrawerDescription asChild>
							<div>
								Your wallet balance is{" "}
								<span className="font-semibold">
									{new Intl.NumberFormat("en-US", {
										minimumFractionDigits: 2,
										maximumFractionDigits: 2,
									}).format(walletBalance)}
								</span>{" "}
							</div>
						</DrawerDescription>
					</DrawerHeader>

					<div className="px-4 flex flex-col gap-4">
						<NumberInput
							label="Set amount to top up"
							value={amount}
							onChange={(value) => setAmount(value)}
							maxAllowed={5000}
							isDisabled={amount === 0}
						/>
					</div>
					<DrawerFooter>
						<Button
							onClick={async () => {
								console.log(data);
								setDisabled(true);
								const topup = await createTopup(data);
								setDisabled(false);
								if (topup) {
									router.push(`/top-ups/${topup.id}`);
									setIsOpen(!isOpen);
								} else {
									toast.error("Something went wrong.");
								}
							}}
							className="w-full"
							disabled={amount === 0 || disabled}
						>
							{disabled ? (
								<Loader2 className="ml-2 animate-spin" />
							) : (
								<>
									Go to payment
									<CircleDollarSign />
								</>
							)}
						</Button>
						<DrawerClose asChild>
							<Button variant="outline">Cancel</Button>
						</DrawerClose>
					</DrawerFooter>
				</div>
			</DrawerContent>
		</Drawer>
	);
}
