"use client"; import React, { useEffect, useRef, useState } from "react"; import { useForm, Controller } 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 { useParams, 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 { createTask, getTask, getUserLevelForAssignments, } from "@/service/task"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { ChevronDown, ChevronUp, Trash2 } from "lucide-react"; import { AudioRecorder } from "react-audio-voice-recorder"; import FileUploader from "@/components/form/shared/file-uploader"; import { Upload } from "tus-js-client"; import { close, error } from "@/config/swal"; import { getCsrfToken } from "@/service/auth"; import { loading } from "@/lib/swal"; import { useTranslations } from "next-intl"; import dynamic from "next/dynamic"; import UpdateSection from "@/app/[locale]/(public)/inbox/update/page"; const taskSchema = z.object({ title: z.string().min(1, { message: "Judul diperlukan" }), naration: z.string().min(2, { message: "Narasi Penugasan harus lebih dari 2 karakter.", }), // url: z.string().min(1, { message: "Judul diperlukan" }), }); interface FileWithPreview extends File { preview: string; } interface Destination { id: string; name: string; subDestination?: SubDestination[]; } interface SubDestination { id: string; name: string; } export type taskDetail = { id: number; title: string; fileTypeOutput: string; assignedToTopLevel: string; assignedToLevel: string; assignmentType: { id: number; name: string; }; assignmentMainType: { id: number; name: string; }; attachmentUrl: string; taskType: string; broadcastType: string; narration: string; is_active: string; }; const CustomEditor = dynamic( () => { return import("@/components/editor/custom-editor"); }, { ssr: false } ); export default function FormTask() { const MySwal = withReactContent(Swal); const router = useRouter(); const editor = useRef(null); type TaskSchema = z.infer; const { id } = useParams() as { id: string }; console.log(id); const [listDest, setListDest] = useState([]); // State for various form fields const [taskOutput, setTaskOutput] = useState({ all: false, video: false, audio: false, image: false, text: false, }); // const [assignmentType, setAssignmentType] = useState("mediahub"); // const [assignmentCategory, setAssignmentCategory] = useState("publication"); const [mainType, setMainType] = useState("1"); const [taskType, setTaskType] = useState("atensi-khusus"); const [broadcastType, setBroadcastType] = useState(""); const [type, setType] = useState("1"); const [selectedTarget, setSelectedTarget] = useState("3,4"); const [detail, setDetail] = useState(); const [refresh] = useState(false); // const [listDest, setListDest] = useState([]); const [checkedLevels, setCheckedLevels] = useState(new Set()); const [expandedPolda, setExpandedPolda] = useState([{}]); const [isLoading, setIsLoading] = useState(false); const [audioFile, setAudioFile] = useState(null); const [isRecording, setIsRecording] = useState(false); const [timer, setTimer] = useState(120); const t = useTranslations("Form"); const [imageFiles, setImageFiles] = useState([]); const [videoFiles, setVideoFiles] = useState([]); const [textFiles, setTextFiles] = useState([]); const [audioFiles, setAudioFiles] = useState([]); const [isImageUploadFinish, setIsImageUploadFinish] = useState(false); const [isVideoUploadFinish, setIsVideoUploadFinish] = useState(false); const [isTextUploadFinish, setIsTextUploadFinish] = useState(false); const [isAudioUploadFinish, setIsAudioUploadFinish] = useState(false); const [voiceNoteLink, setVoiceNoteLink] = useState(""); const [platformTypeVisible, setPlatformTypeVisible] = useState(false); const [unitSelection, setUnitSelection] = useState({ allUnit: false, mabes: false, polda: false, polres: false, satker: false, }); const [links, setLinks] = useState([""]); const { register, control, setValue, handleSubmit, formState: { errors }, } = useForm({ resolver: zodResolver(taskSchema), mode: "all", }); // const handleRadioChange = (event: React.ChangeEvent) => { // const selectedValue = Number(event.target.value); // setMainType(selectedValue); // setPlatformTypeVisible(selectedValue === 2); useEffect(() => { async function fetchPoldaPolres() { setIsLoading(true); try { const response = await getUserLevelForAssignments(); setListDest(response?.data?.data.list); console.log("polda", response?.data?.data?.list); const initialExpandedState = response?.data?.data.list.reduce( (acc: any, polda: any) => { acc[polda.id] = false; return acc; }, {} ); setExpandedPolda(initialExpandedState); console.log("polres", initialExpandedState); } catch (error) { console.error("Error fetching Polda/Polres data:", error); } finally { setIsLoading(false); } } fetchPoldaPolres(); }, []); // }; const handleCheckboxChange = (levelId: number) => { setCheckedLevels((prev) => { const updatedLevels = new Set(prev); if (updatedLevels.has(levelId)) { updatedLevels.delete(levelId); } else { updatedLevels.add(levelId); } return updatedLevels; }); }; const handlePoldaPolresChange = () => { return Array.from(checkedLevels).join(","); }; const handleUnitChange = ( key: keyof typeof unitSelection, value: boolean ) => { if (key === "allUnit") { const newState = { allUnit: value, mabes: value, polda: value, polres: value, satker: value, }; setUnitSelection(newState); console.log("QQQ", newState); } else { const updatedSelection = { ...unitSelection, [key]: value, }; const allChecked = ["mabes", "polda", "polres", "satker"].every( (k) => updatedSelection[k as keyof typeof unitSelection] ); updatedSelection.allUnit = allChecked; setUnitSelection(updatedSelection); console.log("AAA", updatedSelection); } }; const handleTaskOutputChange = ( key: keyof typeof taskOutput, value: boolean ) => { if (key === "all") { const newState = { all: value, video: value, audio: value, image: value, text: value, }; setTaskOutput(newState); } else { const updated = { ...taskOutput, [key]: value, }; const allChecked = ["video", "audio", "image", "text"].every( (k) => updated[k as keyof typeof taskOutput] ); updated.all = allChecked; setTaskOutput(updated); } }; const save = async (data: TaskSchema) => { try { loading(); const fileTypeMapping = { all: "1", video: "2", audio: "4", image: "3", text: "5", }; const unitMapping = { allUnit: "0", mabes: "1", polda: "2", polres: "3", satker: "4", }; const assignmentPurposeString = Object.keys(unitSelection) .filter((key) => unitSelection[key as keyof typeof unitSelection]) .map((key) => unitMapping[key as keyof typeof unitMapping]) .join(","); const selectedOutputs = Object.keys(taskOutput) .filter((key) => taskOutput[key as keyof typeof taskOutput]) .map((key) => fileTypeMapping[key as keyof typeof fileTypeMapping]) .join(","); const requestData = { ...data, assignedToLevel: handlePoldaPolresChange(), assignmentPurpose: assignmentPurposeString, assignedToRole: selectedTarget, taskType, broadcastType, assignmentMainTypeId: mainType, assignmentTypeId: type, fileTypeOutput: selectedOutputs, narration: data.naration, platformType: "", title: data.title, attachmentUrl: links, }; const response = await createTask(requestData); const id = response?.data?.data.id; if (imageFiles?.length === 0) setIsImageUploadFinish(true); else imageFiles.map( async (item, idx) => await uploadResumableFile(idx, String(id), item, "1", "0") ); if (videoFiles?.length === 0) setIsVideoUploadFinish(true); else videoFiles.map( async (item, idx) => await uploadResumableFile(idx, String(id), item, "2", "0") ); if (textFiles?.length === 0) setIsTextUploadFinish(true); else textFiles.map( async (item, idx) => await uploadResumableFile(idx, String(id), item, "3", "0") ); if (audioFiles?.length === 0) setIsAudioUploadFinish(true); else audioFiles.map( async (item, idx) => await uploadResumableFile(idx, String(id), item, "4", "0") ); console.log("PPPPP", requestData); } catch (err) { console.error("Error saat kirim data:", err); close(); error("Terjadi kesalahan saat mengirim data."); } }; useEffect(() => { const updated = new Set(checkedLevels); if (unitSelection.polda) { listDest.forEach((polda) => { updated.add(polda.id); // hanya id polda }); } if (unitSelection.polres) { listDest.forEach((polda) => { polda?.subDestination?.forEach((polres: any) => { updated.add(polres.id); // hanya id polres }); }); } setCheckedLevels(updated); }, [unitSelection.polda, unitSelection.polres, listDest]); 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 toggleExpand = (poldaId: any) => { setExpandedPolda((prev: any) => ({ ...prev, [poldaId]: !prev[poldaId], })); }; const onRecordingStart = () => { setIsRecording(true); const countdown = setInterval(() => { setTimer((prevTimer) => { if (prevTimer <= 1) { clearInterval(countdown); return 0; } return prevTimer - 1; }); }, 1000); setTimeout(() => { if (isRecording) { handleStopRecording(); } }, 120000); }; const handleStopRecording = () => { setIsRecording(false); setTimer(120); }; const addAudioElement = (blob: Blob) => { const url = URL.createObjectURL(blob); const audio = document.createElement("audio"); audio.src = url; audio.controls = true; document.body.appendChild(audio); const fileWithPreview: FileWithPreview = Object.assign( new File([blob], "voiceNote.webm", { type: "audio/webm" }), { preview: url } ); setAudioFile(fileWithPreview); setAudioFiles((prev) => [...prev, fileWithPreview]); }; const handleDeleteAudio = (index: number) => { setAudioFiles((prev) => prev.filter((_, idx) => idx !== index)); }; async function uploadResumableFile( idx: number, id: string, file: any, fileTypeId: string, duration: string ) { console.log(idx, id, file, fileTypeId, duration); const resCsrf = await getCsrfToken(); const csrfToken = resCsrf?.data?.token; console.log("CSRF TOKEN : ", csrfToken); const headers = { "X-XSRF-TOKEN": csrfToken, }; const upload = new Upload(file, { endpoint: `${process.env.NEXT_PUBLIC_API}/assignment/file/upload`, headers: headers, retryDelays: [0, 3000, 6000, 12_000, 24_000], chunkSize: 20_000, metadata: { assignmentId: id, filename: file.name, contentType: file.type, fileTypeId: fileTypeId, duration, }, onBeforeRequest: function (req) { var xhr = req.getUnderlyingObject(); xhr.withCredentials = true; }, onError: async (e: any) => { console.log("Error upload :", e); error(e); }, onChunkComplete: ( chunkSize: any, bytesAccepted: any, bytesTotal: any ) => { // const uploadPersen = Math.floor((bytesAccepted / bytesTotal) * 100); // progressInfo[idx].percentage = uploadPersen; // counterUpdateProgress++; // console.log(counterUpdateProgress); // setProgressList(progressInfo); // setCounterProgress(counterUpdateProgress); }, onSuccess: async () => { // uploadPersen = 100; // progressInfo[idx].percentage = 100; // counterUpdateProgress++; // setCounterProgress(counterUpdateProgress); successTodo(); if (fileTypeId == "1") { setIsImageUploadFinish(true); } if (fileTypeId == "2") { setIsVideoUploadFinish(true); } if (fileTypeId == "3") { setIsTextUploadFinish(true); } if (fileTypeId == "4") { setIsAudioUploadFinish(true); } }, }); upload.start(); } useEffect(() => { successTodo(); }, [ isImageUploadFinish, isVideoUploadFinish, isAudioUploadFinish, isTextUploadFinish, ]); function successTodo() { if ( isImageUploadFinish && isVideoUploadFinish && isAudioUploadFinish && isTextUploadFinish ) { successSubmit("/in/contributor/task"); } } const successSubmit = (redirect: string) => { MySwal.fire({ title: "Sukses", text: "Data berhasil disimpan.", icon: "success", confirmButtonColor: "#3085d6", confirmButtonText: "OK", }).then(() => { router.push(redirect); }); }; const handleLinkChange = (index: number, value: string) => { const updatedLinks = [...links]; updatedLinks[index] = value; setLinks(updatedLinks); }; const handleAddRow = () => { setLinks([...links, ""]); }; const handleRemoveRow = (index: number) => { const updatedLinks = links.filter((_: any, i: any) => i !== index); setLinks(updatedLinks); }; return (

{t("form-task", { defaultValue: "Form Task" })}

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

{errors.title.message}

)}
{Object.keys(unitSelection).map((key) => { const isDisabled = key === "polres" && !unitSelection.polda; return (
handleUnitChange( key as keyof typeof unitSelection, value as boolean ) } />
); })}
Daftar Wilayah Polda dan Polres
{listDest.map((polda: any) => { const poldaChecked = unitSelection.polda; // kontrol polda luar const polresChecked = unitSelection.polres; // kontrol polres luar const isPoldaDisabled = poldaChecked; // lock checkbox polda dialog jika polda luar dicentang const isPolresDisabled = polresChecked; // lock checkbox polres dialog jika polres luar dicentang return (
{expandedPolda[polda.id] && (
{polda?.subDestination?.map((polres: any) => ( ))}
)}
); })}
setMainType(value)} // value={String(mainType)} // onValueChange={(value) => setMainType(Number(value))} className="flex flex-wrap gap-3" >
setTaskType(String(value))} className="flex flex-wrap gap-3" >
{/* RadioGroup Assignment Category */}
setType(value)} // Mengubah nilai state ketika pilihan berubah className="flex flex-wrap gap-3" >
{Object.keys(taskOutput).map((key) => (
handleTaskOutputChange( key as keyof typeof taskOutput, value as boolean ) } />
))}
{/*
setBroadcastType(value)} // Mengatur nilai saat radio berubah className="flex flex-wrap gap-3" >
*/}
( )} /> {errors.naration?.message && (

{errors.naration.message}

)}
setVideoFiles(files)} />
setImageFiles(files)} />
setTextFiles(files)} />
setAudioFiles((prev) => [...prev, ...files]) } className="mt-2" />
{audioFiles?.map((audio: any, idx: any) => (

{t("voice-note", { defaultValue: "Voice Note" })}

))} {isRecording &&

Recording... {timer} seconds remaining

}{" "} {/* Display remaining time */}
{links.map((link, index) => (
handleLinkChange(index, e.target.value) } /> {links.length > 1 && ( )}
))}
{/* Submit Button */}
); }