"use client"; import { useEffect, useState } from "react"; import Image from "next/image"; import Cookies from "js-cookie"; import Swal from "sweetalert2"; import withReactContent from "sweetalert2-react-content"; import { getPromotionById, updatePromotion } from "@/service/promotion"; import { Button } from "@/components/ui/button"; import { loading, success, error } from "@/config/swal"; type PromoEditDialogProps = { promoId: number | null; open: boolean; onOpenChange: (open: boolean) => void; onSuccess?: () => void; }; export default function PromoEditDialog({ promoId, open, onOpenChange, onSuccess, }: PromoEditDialogProps) { const [loadingData, setLoadingData] = useState(false); // 🔹 FORM STATE const [title, setTitle] = useState(""); const [thumbnailUrl, setThumbnailUrl] = useState(null); const [thumbnailFile, setThumbnailFile] = useState(null); const MySwal = withReactContent(Swal); /* ========================= * Fetch promo detail ========================= */ useEffect(() => { if (!promoId || !open) return; async function fetchPromo() { try { setLoadingData(true); const res = await getPromotionById(promoId); const data = res?.data?.data; setTitle(data?.title || ""); setThumbnailUrl(data?.thumbnail_url || null); } catch (e) { console.error("FETCH PROMO ERROR:", e); } finally { setLoadingData(false); } } fetchPromo(); }, [promoId, open]); if (!open) return null; /* ========================= * Handlers ========================= */ const handleFileChange = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; setThumbnailFile(file); setThumbnailUrl(URL.createObjectURL(file)); }; const handleSubmit = async () => { if (!promoId) return; const formData = new FormData(); formData.append("title", title); if (thumbnailFile) { formData.append("file", thumbnailFile); } loading(); const res = await updatePromotion(formData, promoId); if (res?.error) { error(res.message || "Gagal update promo"); return; } success("Promo berhasil diperbarui"); onOpenChange(false); onSuccess?.(); }; /* ========================= * Render ========================= */ return (
onOpenChange(false)} >
e.stopPropagation()} > {/* HEADER */}

Edit Promo

{/* BODY */}
{loadingData ? (

Memuat data...

) : ( <> {/* TITLE */}
setTitle(e.target.value)} className="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-[#0F6C75]" placeholder="Judul promo" />
{/* THUMBNAIL */}
{thumbnailUrl && (
Thumbnail
)}
)}
{/* FOOTER */}
); }