"use client"; import React, { ChangeEvent, useEffect, useRef, useState } from "react"; import { useForm, Controller, useWatch } from "react-hook-form"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Card } from "@/components/ui/card"; import { zodResolver } from "@hookform/resolvers/zod"; import * as z from "zod"; import Swal from "sweetalert2"; import withReactContent from "sweetalert2-react-content"; import { useRouter } from "next/navigation"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Checkbox } from "@/components/ui/checkbox"; import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"; import { register } from "module"; import { Switch } from "@/components/ui/switch"; import Cookies from "js-cookie"; import { createMedia, getTagsBySubCategoryId, listEnableCategory, } from "@/service/content/content"; import { postBlog, uploadThumbnailBlog } from "@/service/blog/blog"; import dynamic from "next/dynamic"; import { error } from "console"; import { loading } from "@/lib/swal"; import { getCookiesDecrypt } from "@/lib/utils"; const taskSchema = z.object({ title: z.string().min(1, { message: "Judul diperlukan" }), slug: z.string().min(1, { message: "Judul diperlukan" }), meta: z.string().min(1, { message: "Judul diperlukan" }), narration: z .string() .min(2, { message: "Narasi Penugasan harus lebih dari 2 karakter." }), }); type Category = { id: string; name: string; }; const initialCategories: Category[] = [ { id: "1", name: "Giat Polri", }, { id: "2", name: "Giat Pimpinan", }, { id: "3", name: "Liputan Kegiatan", }, { id: "4", name: "Seputar Prestasi", }, ]; const CustomEditor = dynamic( () => { return import("@/components/editor/custom-editor"); }, { ssr: false } ); export default function FormBlog() { const MySwal = withReactContent(Swal); const router = useRouter(); const editor = useRef(null); type TaskSchema = z.infer; const [selectedFiles, setSelectedFiles] = useState([]); const taskId = Cookies.get("taskId"); const scheduleId = Cookies.get("scheduleId"); const scheduleType = Cookies.get("scheduleType"); const [categories] = useState(initialCategories); // State untuk kategori const [selectedTarget, setSelectedTarget] = useState(""); const [selectedCategory, setSelectedCategory] = useState(); const [tags, setTags] = useState([]); const [isDraft, setIsDraft] = useState(false); const [thumbnail, setThumbnail] = useState(null); const [preview, setPreview] = useState(null); const inputRef = useRef(null); const roleName = getCookiesDecrypt("urne"); const [unitSelection, setUnitSelection] = useState({ allUnit: false, mabes: false, polda: false, polres: false, }); let fileTypeId = "1"; const { control, handleSubmit, setValue, formState: { errors }, } = useForm({ resolver: zodResolver(taskSchema), }); // const handleKeyDown = (e: any) => { // const newTag = e.target.value.trim(); // Ambil nilai input // if (e.key === "Enter" && newTag) { // e.preventDefault(); // Hentikan submit form // if (!tags.includes(newTag)) { // setTags((prevTags) => [...prevTags, newTag]); // Tambah tag baru // setValue("tags", ""); // Kosongkan input // } // } // }; const handleRemoveTag = (index: any) => { setTags((prevTags) => prevTags.filter((_, i) => i !== index)); }; const handleRemoveImage = (index: number) => { setSelectedFiles((prevImages) => prevImages.filter((_, i) => i !== index)); }; const titleValue = useWatch({ control, name: "title" }); useEffect(() => { if (titleValue) { const slugified = titleValue .toLowerCase() .trim() .replace(/\s+/g, "-") .replace(/[^\w-]+/g, ""); // optional: hapus karakter non-alfanumerik setValue("slug", slugified); } }, [titleValue, setValue]); // useEffect(() => { // async function initState() { // getCategories(); // // setVideoActive(fileTypeId == '2'); // // getRoles(); // } // initState(); // }, []); // const getCategories = async () => { // try { // const category = await listEnableCategory(fileTypeId); // const resCategory: Category[] = category?.data?.data?.content; // setCategories(resCategory); // console.log("data category", resCategory); // if (scheduleId && scheduleType === "3") { // const findCategory = resCategory.find((o) => // o.name.toLowerCase().includes("pers rilis") // ); // if (findCategory) { // // setValue("categoryId", findCategory.id); // setSelectedCategory(findCategory.id); // Set the selected category // const response = await getTagsBySubCategoryId(findCategory.id); // setTags(response?.data?.data); // } // } // } catch (error) { // console.error("Failed to fetch categories:", error); // } // }; const save = async (data: TaskSchema) => { loading(); console.log("roleName", roleName); const finalTags = tags.join(", "); const requestData = { ...data, title: data.title, narration: data.narration, categoryId: selectedTarget, slug: data.slug, metadata: data.meta, tags: finalTags, isDraft, isInternational: roleName?.includes("INT") ? true : false, }; const response = await postBlog(requestData); console.log("Form Data Submitted:", requestData); console.log("response", response); if (response?.error) { MySwal.fire("Error", response?.message, "error"); return; } const blogId = response?.data?.data?.id; if (blogId) { if (thumbnail) { const formMedia = new FormData(); formMedia.append("file", thumbnail); // Tambahkan file ke FormData console.log("FormMedia:", formMedia.get("file")); const responseThumbnail = await uploadThumbnailBlog(blogId, formMedia); if (responseThumbnail?.error) { MySwal.fire("Error", responseThumbnail?.message, "error"); return; } } else { console.log("No thumbnail to upload"); } } close(); MySwal.fire({ title: "Sukses", text: "Data berhasil disimpan.", icon: "success", confirmButtonColor: "#3085d6", confirmButtonText: "OK", }).then(() => { router.push("/in/contributor/blog"); }); }; const onSubmit = (data: TaskSchema) => { MySwal.fire({ title: "Simpan Data", text: "Apakah Anda yakin ingin menyimpan data ini?", icon: "warning", showCancelButton: true, cancelButtonColor: "#d33", confirmButtonColor: "#3085d6", confirmButtonText: "Simpan", }).then((result) => { if (result.isConfirmed) { save(data); } }); }; const handleImageChange = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (file) { setThumbnail(file); // Simpan file ke state setPreview(URL.createObjectURL(file)); // Buat URL untuk preview console.log("Selected Thumbnail:", file); } else { console.log("No file selected"); } }; const handlePublish = () => { setIsDraft(false); }; const handleSave = () => { setIsDraft(true); }; const handleAddTag = (e: React.KeyboardEvent) => { if (e.key === "Enter" && e.currentTarget.value.trim()) { e.preventDefault(); const newTag = e.currentTarget.value.trim(); if (!tags.includes(newTag)) { setTags((prevTags) => [...prevTags, newTag]); // Add new tag if (inputRef.current) { inputRef.current.value = ""; // Clear input field } } } }; return (

Form Indeks

{/* Input Title */}
( )} /> {errors.title?.message && (

{errors.title.message}

)}
( )} /> {errors.narration?.message && (

{errors.narration.message}

)}
( )} /> {errors.slug?.message && (

{errors.slug.message}

)}
( )} /> {errors.meta?.message && (

{errors.meta.message}

)}
{preview && (
Thumbnail Preview
)}
{tags.map((tag, index) => ( {tag}{" "} ))}
{/*
{tags.length === 0 && "Please add at least one tag."}
{tags.map((tag, index) => (
{tag}
))}
*/}
); }