"use client";

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, Payment } from "@/lib/backend-types";
import { tryCatch } from "@/utils/tryCatch";
import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { CircleDollarSign, Loader2 } from "lucide-react";
import { useSession } from "next-auth/react";
import { redirect, usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
export default function DevicesForPayment() {
	const baseAmount = 100;
	const discountPercentage = 75;
	const session = useSession();
	const pathname = usePathname();
	const devices = useAtomValue(deviceCartAtom);
	const setDeviceCart = useSetAtom(deviceCartAtom);
	const [months, setMonths] = useAtom(numberOfMonths);
	const [message, setMessage] = useState("");
	const [disabled, setDisabled] = useState(false);
	const [total, setTotal] = useState(0);
	useEffect(() => {
		if (months === 7) {
			setMessage("You will get 1 month free.");
		} else if (months === 12) {
			setMessage("You will get 2 months free.");
		} else {
			setMessage("");
		}
		setTotal(baseAmount + (devices.length + 1 - 1) * discountPercentage);
	}, [months, devices.length]);

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

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

	if (disabled) {
		return "Please wait...";
	}
	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}
				/>
				{message && (
					<span className="title-bg text-lime-800 bg-lime-100/50 dark:text-lime-100 rounded text-center p-2 w-full">
						{message}
					</span>
				)}
			</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>
	);
}
