"use client"; import { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { Form, FormControl, FormField, FormItem, FormLabel, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { Checkbox } from "@/components/ui/checkbox"; import { Button } from "@/components/ui/button"; import { getAgentById, updateAgent } from "@/service/agent"; import { useRouter } from "next/navigation"; import Swal from "sweetalert2"; import withReactContent from "sweetalert2-react-content"; import { X } from "lucide-react"; type AgentFormValues = { fullName: string; position: string; phone: string; roles: string[]; }; const AGENT_TYPES = ["after-Sales", "sales", "spv", "branch_manager"]; export default function UpdateAgentForm({ id }: { id: number }) { const router = useRouter(); const MySwal = withReactContent(Swal); const [loading, setLoading] = useState(true); const [file, setFile] = useState(null); const [preview, setPreview] = useState(null); const [agentData, setAgentData] = useState(null); const form = useForm({ defaultValues: { fullName: "", position: "", phone: "", roles: [], }, }); /* ================= FETCH DATA ================= */ useEffect(() => { async function fetchData() { try { const res = await getAgentById(id); const agent = res?.data?.data; if (!agent) return; setAgentData(agent); form.reset({ fullName: agent.name, position: agent.job_title, phone: agent.phone, roles: agent.job_title ? [agent.job_title] : [], }); // ✅ FOTO DARI API setPreview(agent.profile_picture_url ?? null); } catch (error) { console.error("FETCH AGENT ERROR:", error); } finally { setLoading(false); } } fetchData(); }, [id, form]); /* ================= FILE HANDLER ================= */ const handleFileChange = (e: React.ChangeEvent) => { const selected = e.target.files?.[0]; if (!selected) return; setFile(selected); setPreview(URL.createObjectURL(selected)); }; const handleRemoveFile = () => { setFile(null); setPreview(agentData?.profile_picture_url ?? null); }; /* ================= SUBMIT ================= */ const onSubmit = async (data: AgentFormValues) => { try { const formData = new FormData(); formData.append("name", data.fullName); formData.append("job_title", data.roles[0]); // single role formData.append("phone", data.phone); if (file) { formData.append("file", file); } await updateAgent(id, formData); MySwal.fire({ title: "Berhasil", text: "Data agen berhasil diperbarui", icon: "success", }).then(() => router.push("/admin/agent")); } catch (error) { console.error("UPDATE AGENT ERROR:", error); } }; if (loading) return

Loading...

; return (

Edit Agen

{/* BASIC INFO */}
( Nama Lengkap )} /> ( Jabatan )} /> ( No Telp )} />
{/* JENIS AGEN */}
Jenis Agen
{AGENT_TYPES.map((role) => ( ( field.onChange(checked ? [role] : []) } /> {role.replace("_", " ")} )} /> ))}
{/* FOTO */}
Foto Agen
{preview && (
Foto Agen
)}
{/* BUTTON */}
); }