"use client";

import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { CircleDollarSign, Loader2 } from "lucide-react";
import { redirect, usePathname } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { createPayment } from "@/actions/payment";
import DeviceCard from "@/components/device-card";
import NumberInput from "@/components/number-input";
import { Button } from "@/components/ui/button";
import { deviceCartAtom, numberOfMonths } from "@/lib/atoms";
import type { NewPayment } from "@/lib/backend-types";
import { tryCatch } from "@/utils/tryCatch";
import FullPageLoader from "./full-page-loader";
export default function DevicesForPayment() {
	const pathname = usePathname();
	const devices = useAtomValue(deviceCartAtom);
	const setDeviceCart = useSetAtom(deviceCartAtom);
	const [months, setMonths] = useAtom(numberOfMonths);
	const [disabled, setDisabled] = useState(false);


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

	const data: NewPayment = {
		number_of_months: months,
		device_ids: devices.map((device) => device.id),
	};

	if (disabled) {
		return <FullPageLoader />;
	}
	return (
		<div className="max-w-lg mx-auto space-y-4 px-4">
			<div className="flex max-h-[calc(100svh-400px)] flex-col overflow-auto pb-4 gap-4">
				{devices.map((device) => (
					<DeviceCard key={device.id} device={device} />
				))}
			</div>
			<div className="flex flex-col gap-4">
				<NumberInput
					label="Set No of Months"
					value={months}
					onChange={(value: number) => setMonths(value)}
					maxAllowed={12}
					isDisabled={devices.length === 0}
				/>

			</div>
			<Button
				onClick={async () => {
					setDisabled(true);
					const [error, response] = await tryCatch(createPayment(data));
					if (error) {
						setDisabled(false);
						toast.error(JSON.stringify(error, null, 2));
						return;
					}
					setDeviceCart([]);
					setMonths(1);
					redirect(`/payments/${response.id}`);
				}}
				className="w-full"
				disabled={devices.length === 0 || disabled}
			>
				{disabled ? (
					<>
						<Loader2 className="ml-2 animate-spin" />
					</>
				) : (
					<>
						Go to payment
						<CircleDollarSign />
					</>
				)}
			</Button>
		</div>
	);
}
