"use client";
import { Loader2, MoveLeft } from "lucide-react";
import { useActionState, useEffect } from "react";
import { toast } from "sonner";
import {
	type UpdateUserFormState,
	updateUserAgreement,
} from "@/actions/user-actions";
import { Button } from "@/components/ui/button";
import { FloatingLabelInput } from "@/components/ui/floating-label";
import type { UserProfile } from "@/lib/types/user";

export default function UserAgreementForm({ user }: { user: UserProfile }) {
	const initialState: UpdateUserFormState = {
		message: "",
		fieldErrors: {},
		payload: new FormData(),
	};
	const [state, formAction, isPending] = useActionState(
		updateUserAgreement,
		initialState,
	);

	useEffect(() => {
		if (state.message) {
			if (state.fieldErrors) {
				Object.entries(state.fieldErrors).forEach(([field, errors]) => {
					errors.forEach((error) => {
						toast.error(`Error in ${field}: ${error}`);
					});
				});
			} else {
				toast.success("Success", {
					description: "User agreement updated successfully",
					closeButton: true,
				});
			}
		}
	}, [state]);

	return (
		<div id="user-update-form">
			<Button
				onClick={() => window.history.back()}
				variant="outline"
				className="mb-4"
			>
				<MoveLeft />
				Go Back
			</Button>
			<form action={formAction}>
				<h4 className="p-2 rounded font-semibold text-muted-foreground">
					Upload User agreement
				</h4>
				<div className="border border-dashed border-sarLinkOrange p-4 rounded-lg  max-w-2xl">
					<fieldset
						disabled={isPending}
						className="space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-4"
					>
						<input type="hidden" name="userId" value={user.id} />
						<FloatingLabelInput
							type="file"
							size={10}
							name="agreement"
							label="Agreement Document"
							accept=".pdf"
						/>
					</fieldset>

					<Button
						disabled={isPending}
						type="submit"
						variant={"secondary"}
						className=""
					>
						{isPending ? (
							<Loader2 className="animate-spin" />
						) : (
							"Update Agreement"
						)}
					</Button>
				</div>
			</form>
		</div>
	);
}
