"use client"; import React, { useState } from "react"; import { useRouter } from "next/navigation"; import { toast } from "react-hot-toast"; export interface CreditCardApplication { name: string; email: string; phone: string; nationality: string; salary: number; agree: boolean; } interface CreditCardApplyFormProps { cardId: number; cardName: string; returnUrl: string; } const CreditCardApplyForm: React.FC = ({ cardId, cardName, returnUrl, }) => { const router = useRouter(); const [form, setForm] = useState({ name: "", email: "", phone: "", nationality: "", salary: 0, agree: false, }); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [successMsg, setSuccessMsg] = useState(null); const handleChange = ( e: React.ChangeEvent ) => { const target = e.target as HTMLInputElement; const { name, value, type } = target; setForm((prev) => ({ ...prev, [name]: type === "checkbox" ? target.checked : type === "number" ? Number(value) : value, })); }; const validate = (): boolean => { if (!form.name.trim()) return setError("Name is required"), false; if (!form.email.trim() || !/\S+@\S+\.\S+/.test(form.email)) return setError("Valid email is required"), false; if (!form.phone.trim()) return setError("Phone number is required"), false; if (!form.nationality.trim()) return setError("Nationality is required"), false; if (form.salary <= 0) return setError("Salary must be greater than zero"), false; if (!form.agree) return setError("You must agree to the terms"), false; setError(null); return true; }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!validate()) return; setLoading(true); setError(null); setSuccessMsg(null); try { const response = await fetch(`/api/applycard/${cardId}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...form, cardId }), }); const data = await response.json(); if (!response.ok) { toast.error(data.error || "Failed to submit application"); } else { //setSuccessMsg("Application submitted successfully!"); toast.success("Application submitted successfully!"); setForm({ name: "", email: "", phone: "", nationality: "", salary: 0, agree: false, }); // ✅ Redirect to return URL setTimeout(() => { router.push(returnUrl); }, 1500); // Optional delay (1.5s) } } catch (err) { toast.error(err instanceof Error ? err.message : "An unexpected error occurred"); } finally { setLoading(false); } }; return (

Apply for: {cardName}

{error &&

{error}

} {successMsg &&

{successMsg}

}
); }; export default CreditCardApplyForm;