"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import Image from "next/image"; type Country = { id: string; name: string }; type CardTier = "GOLD" | "SILVER" | "BRONZE"; export default function PlayerForm({ countries, initial, playerId, }: { countries: Country[]; initial?: { name: string; position: string; countryId: string; price: number; image?: string | null; cardTier: CardTier }; playerId?: string; }) { const router = useRouter(); const [form, setForm] = useState({ name: initial?.name ?? "", position: initial?.position ?? "FWD", countryId: initial?.countryId ?? "", price: initial?.price ?? 5.0, image: initial?.image ?? "", cardTier: initial?.cardTier ?? "BRONZE", }); const [loading, setLoading] = useState(false); const [uploading, setUploading] = useState(false); const [error, setError] = useState(""); async function handleImageUpload(e: React.ChangeEvent) { const file = e.target.files?.[0]; if (!file) return; setUploading(true); setError(""); const formData = new FormData(); formData.append("file", file); try { const res = await fetch("/api/upload/player-image", { method: "POST", body: formData, }); if (res.ok) { const data = await res.json(); setForm({ ...form, image: data.fileName }); } else { const data = await res.json(); setError(data.error ?? "خطا در آپلود تصویر"); } } catch (err) { setError("خطا در آپلود تصویر"); } finally { setUploading(false); } } async function handleSubmit(e: React.FormEvent) { e.preventDefault(); setLoading(true); const res = await fetch(playerId ? `/api/players/${playerId}` : "/api/players", { method: playerId ? "PUT" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form), }); if (res.ok) { router.push("/admin/players"); router.refresh(); } else { const d = await res.json(); setError(d.error ?? "خطا"); } setLoading(false); } return (
{error &&

{error}

}
{form.image && (
{form.name}
)}
{uploading &&

در حال آپلود...

}
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, price: parseFloat(e.target.value) })} className="w-full border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500" />
); }