"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; type Group = { id: string; name: string }; export default function CountryForm({ groups, initial, countryId, }: { groups: Group[]; initial?: { name: string; code: string; flagUrl?: string | null; groupId?: string | null }; countryId?: string; }) { const router = useRouter(); const [form, setForm] = useState({ name: initial?.name ?? "", code: initial?.code ?? "", flagUrl: initial?.flagUrl ?? "", groupId: initial?.groupId ?? "", }); const [loading, setLoading] = useState(false); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); setLoading(true); const payload = { ...form, groupId: form.groupId || null, flagUrl: form.flagUrl || null }; const res = await fetch(countryId ? `/api/countries/${countryId}` : "/api/countries", { method: countryId ? "PUT" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); if (res.ok) { router.push("/admin/countries"); router.refresh(); } setLoading(false); } return (
setForm({ ...form, name: e.target.value })} className="w-full border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500" required />
setForm({ ...form, code: e.target.value.toUpperCase() })} maxLength={3} className="w-full border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500" required />
setForm({ ...form, flagUrl: e.target.value })} placeholder="🇮🇷" className="w-full border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500" />
); }