"use client";

import { Loader2, PlusCircle } from "lucide-react";
import { useRouter } from "next/navigation";
import { useActionState, useEffect, useState } from "react"; // Import useActionState
import { toast } from "sonner";
import { adminUserTopup } from "@/actions/user-actions";
import { Button } from "@/components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogFooter,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "../ui/textarea";

export type AddTopupFormState = {
	status: boolean;
	message: string;
	fieldErrors?: {
		amount?: string[];
		description?: string[];
	};
	payload?: FormData;
};

export const initialState: AddTopupFormState = {
	message: "",
	fieldErrors: {},
	status: false,
};

export default function AddTopupDialogForm({ user_id }: { user_id?: string }) {
	const [open, setOpen] = useState(false);
	const router = useRouter();
	const [state, formAction, pending] = useActionState(
		adminUserTopup,
		initialState,
	);

	useEffect(() => {
		if (state.message && state !== initialState) {
			if (state.fieldErrors && Object.keys(state.fieldErrors).length > 0) {
				toast.error(state.message);
			} else if (state.status) {
				setOpen(false);
				toast.success(state.message);
				router.push("/user-topups?page=1");
			} else {
				toast.error(state.message);
			}
		}
	}, [state, router]);

	if (!user_id) {
		return null;
	}

	return (
		<Dialog open={open} onOpenChange={setOpen}>
			<DialogTrigger asChild>
				<Button
					className="gap-2 items-center"
					disabled={pending}
					variant="default"
				>
					Add cash topup
					<PlusCircle size={16} />
				</Button>
			</DialogTrigger>
			<DialogContent className="sm:max-w-[425px]">
				<DialogHeader>
					<DialogTitle>New Manual Topup</DialogTitle>
					<DialogDescription>
						To add a new manual topup, enter the amount below. Click save when
						you are done.
					</DialogDescription>
				</DialogHeader>
				<form action={formAction}>
					<div className="grid gap-4 py-4">
						<div className="flex flex-col gap-3">
							<div className="flex flex-col gap-3">
								<Label htmlFor="amount">Topup Amount</Label>
								<input type="hidden" name="user_id" value={user_id} />
								<Input
									type="number"
									defaultValue={(state?.payload?.get("amount") || "") as string}
									name="amount"
									id="topup_amount"
									className="col-span-3"
								/>
								{state.fieldErrors?.amount && (
									<span className="text-red-500 text-sm">
										{state.fieldErrors.amount[0]}
									</span>
								)}
							</div>
							<div className="flex flex-col gap-3">
								<Label htmlFor="description">Topup Description</Label>
								<input type="hidden" name="user_id" value={user_id} />
								<Textarea
									defaultValue={
										(state?.payload?.get("description") || "") as string
									}
									rows={10}
									name="description"
									id="topup_description"
									className="col-span-5 max-w-[375px] h-32 resize-none"
									style={{ overflowY: "auto" }}
								/>
								{state.fieldErrors?.description && (
									<span className="text-red-500 text-sm">
										{state.fieldErrors.description[0]}
									</span>
								)}
							</div>
						</div>
					</div>
					<DialogFooter>
						<Button disabled={pending} type="submit">
							{pending ? <Loader2 className="animate-spin" /> : "Save"}
						</Button>
					</DialogFooter>
				</form>
			</DialogContent>
		</Dialog>
	);
}
