"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, createTaskTa, getTask, getUserLevelForAssignments, getUserLevelForExpert, } from "@/service/task"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { CalendarIcon, 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 { 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 { cn, getCookiesDecrypt } from "@/lib/utils"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { Calendar } from "@/components/ui/calendar"; import { addDays, format, setDate } from "date-fns"; import { DateRange } from "react-day-picker"; import TimePicker from "react-time-picker"; import "react-time-picker/dist/TimePicker.css"; import "react-clock/dist/Clock.css"; import { AdministrationLevelList, getListCompetencies, getListExperiences, } from "@/service/management-user/management-user"; const taskSchema = z.object({ title: z.string().min(1, { message: "Judul diperlukan" }), narration: 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; } 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 FormTaskTa() { 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 [expertise, setExpertiseOutput] = useState({ semua: false, komunikasi: false, hukum: false, bahasa: false, ekonomi: false, politik: false, sosiologi: false, ilmuadministrasipemerintah: false, ti: false, }); const [expert, setExpertOutput] = useState({ semua: false, }); 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 [userExperiences, setUserExperiences] = useState(); const [userLevels, setUserLevels] = useState(); const [userCompetencies, setUserCompetencies] = useState([]); const [selectedCompetencies, setSelectedCompetencies] = useState>( new Set() ); const [listExpert, setListExpert] = 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 [date, setDate] = React.useState({ from: new Date(), }); const [platformTypeVisible, setPlatformTypeVisible] = useState(false); const [unitSelection, setUnitSelection] = useState({ semua: 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 [profile, setProfile] = useState(null); const userLevelId = Number(getCookiesDecrypt("ulie")); const roleId = Number(getCookiesDecrypt("urie")); const userId = Number(getCookiesDecrypt("uie")); const MABES_LEVEL_ID = 216; // userLevelId Mabes Polri const APPROVER_ROLE_ID = 3; // roleId Approver const isMabes = userLevelId === MABES_LEVEL_ID; const isApprover = roleId === APPROVER_ROLE_ID; const isMabesApprover = userLevelId === MABES_LEVEL_ID && roleId === APPROVER_ROLE_ID; const shouldHideExpert = isMabes && isApprover; useEffect(() => { async function fetchUserLevel() { try { const res = await getUserLevelForAssignments(); setProfile(res?.data?.data); } catch (e) { console.error("Failed fetch user level", e); } } fetchUserLevel(); }, []); useEffect(() => { getDataAdditional(); }, []); async function getDataAdditional() { const resCompetencies = await getListCompetencies(); console.log("competency", resCompetencies); setUserCompetencies(resCompetencies?.data?.data); } useEffect(() => { async function fetchListExpert() { setIsLoading(true); try { const response = await getUserLevelForExpert(id); setListExpert(response?.data?.data); console.log("tenaga ahli", response?.data?.data); } catch (error) { console.error("Error fetching Polda/Polres data:", error); } finally { setIsLoading(false); } } fetchListExpert(); }, []); useEffect(() => { const fetchExpertsForCompetencies = async () => { const allExperts: any[] = []; for (const compId of Array.from(selectedCompetencies)) { const response = await getUserLevelForExpert(compId); const experts = response?.data?.data || []; allExperts.push(...experts); } const uniqueExperts = Array.from( new Map(allExperts.map((e) => [e.id, e])).values() ); setListExpert(uniqueExperts); }; if (selectedCompetencies.size > 0) { fetchExpertsForCompetencies(); } else { setListExpert([]); } }, [selectedCompetencies]); // }; 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 handleExpertChange = () => { return Array.from(checkedLevels).join(","); }; const handleCompetencyChange = async (competencyId: number) => { setSelectedCompetencies((prev) => { const updated = new Set(prev); if (updated.has(competencyId)) { updated.delete(competencyId); } else { updated.add(competencyId); } return updated; }); }; // const save = async (data: TaskSchema) => { // const cleanedLinks = links // .map((link) => link.trim()) // .filter((link) => link !== "" && link.startsWith("http")); // const requestData: { // id?: number; // title: string; // assignedToUsers: any; // assignmentTypeId: string; // narration: string; // assignmentType: string; // expertCompetencies: string; // attachmentUrl: string[]; // } = { // ...data, // assignedToUsers: handleExpertChange(), // assignmentType: taskType, // assignmentTypeId: type, // narration: data.narration, // expertCompetencies: Array.from(selectedCompetencies).join(","), // title: data.title, // attachmentUrl: cleanedLinks, // }; // const response = await createTaskTa(requestData); // localStorage.setItem("TA_UPLOAD_IN_PROGRESS", "true"); // console.log("Form Data Submitted:", requestData); // console.log("response", response); // const id = response?.data?.data.id; // loading(); // if (imageFiles?.length == 0) { // setIsImageUploadFinish(true); // } // const allUploads: Promise[] = []; // imageFiles.forEach((item, index) => { // allUploads.push(uploadResumableFile(index, String(id), item, "1", "0")); // }); // videoFiles.forEach((item, index) => { // allUploads.push(uploadResumableFile(index, String(id), item, "2", "0")); // }); // textFiles.forEach((item, index) => { // allUploads.push(uploadResumableFile(index, String(id), item, "3", "0")); // }); // audioFiles.forEach((item, index) => { // allUploads.push(uploadResumableFile(index, String(id), item, "4", "0")); // }); // // ⬅ WAJIB // await Promise.all(allUploads); // localStorage.removeItem("TA_UPLOAD_IN_PROGRESS"); // // imageFiles?.map(async (item: any, index: number) => { // // await uploadResumableFile(index, String(id), item, "1", "0"); // // }); // // if (videoFiles?.length == 0) { // // setIsVideoUploadFinish(true); // // } // // videoFiles?.map(async (item: any, index: number) => { // // await uploadResumableFile(index, String(id), item, "2", "0"); // // }); // // if (textFiles?.length == 0) { // // setIsTextUploadFinish(true); // // } // // textFiles?.map(async (item: any, index: number) => { // // await uploadResumableFile(index, String(id), item, "3", "0"); // // }); // // if (audioFiles?.length == 0) { // // setIsAudioUploadFinish(true); // // } // // audioFiles.map(async (item: FileWithPreview, index: number) => { // // await uploadResumableFile( // // index, // // String(id), // // item, // Use .file to access the actual File object // // "4", // // "0" // Optional: Replace with actual duration if available // // ); // // }); // }; // const save = async (data: TaskSchema) => { // const cleanedLinks = links // .map((link) => link.trim()) // .filter((link) => link.startsWith("http")); // const requestData = { // ...data, // // assignedToUsers: handleExpertChange(), // assignedToUsers: isMabesApprover ? "464" : handleExpertChange(), // assignmentType: taskType, // assignmentTypeId: type, // expertCompetencies: Array.from(selectedCompetencies).join(","), // attachmentUrl: cleanedLinks, // }; // console.log("FINAL ASSIGNED TO:", { // isMabesApprover, // assignedToUsers: isMabesApprover // ? String(roleId) // : handleExpertChange(), // }); // const response = await createTaskTa(requestData); // const id = String(response?.data?.data.id); // // Set block table TA // localStorage.setItem("TA_UPLOAD_IN_PROGRESS", "true"); // loading(); // SHOW SWAL LOADING // // Kumpulkan semua upload // const allUploads: Promise[] = []; // imageFiles.forEach((item, idx) => // allUploads.push(uploadResumableFile(idx, id, item, "1", "0")) // ); // videoFiles.forEach((item, idx) => // allUploads.push(uploadResumableFile(idx, id, item, "2", "0")) // ); // textFiles.forEach((item, idx) => // allUploads.push(uploadResumableFile(idx, id, item, "3", "0")) // ); // audioFiles.forEach((item, idx) => // allUploads.push(uploadResumableFile(idx, id, item, "4", "0")) // ); // // Tunggu upload selesai // await Promise.all(allUploads); // // Hapus flag // localStorage.removeItem("TA_UPLOAD_IN_PROGRESS"); // // Close loading + redirect // successSubmit("/in/contributor/task-ta"); // }; const save = async (data: TaskSchema) => { try { loading(); const cleanedLinks = links .map((link) => link.trim()) .filter((link) => link.startsWith("http")); const requestData = { ...data, // assignedToUsers: isMabesApprover ? "464" : handleExpertChange(), assignedToUsers: isMabesApprover ? ["464", "8258"] : handleExpertChange(), assignmentType: taskType, assignmentTypeId: type, expertCompetencies: Array.from(selectedCompetencies).join(","), attachmentUrl: cleanedLinks, }; const response = await createTaskTa(requestData); if (!response?.data?.data?.id) { throw new Error("Gagal membuat task"); } const assignmentId = String(response.data.data.id); const uploads: Promise[] = []; imageFiles.forEach((file, i) => uploads.push(uploadResumableFile(i, assignmentId, file, "1", "0")) ); videoFiles.forEach((file, i) => uploads.push(uploadResumableFile(i, assignmentId, file, "2", "0")) ); textFiles.forEach((file, i) => uploads.push(uploadResumableFile(i, assignmentId, file, "3", "0")) ); audioFiles.forEach((file, i) => uploads.push(uploadResumableFile(i, assignmentId, file, "4", "0")) ); await Promise.all(uploads); successSubmit("/in/contributor/task-ta"); } catch (err: any) { console.error("SUBMIT ERROR:", err); Swal.fire({ icon: "error", title: "Gagal", text: err?.response?.data?.message || err?.message || "Terjadi kesalahan, data tidak tersimpan", }); } }; 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); // Reset the timer to 2 minutes for the next recording }; const addAudioElement = (blob: Blob) => { const url = URL.createObjectURL(blob); const audio = document.createElement("audio"); audio.src = url; audio.controls = true; document.body.appendChild(audio); // Convert Blob to File and add preview const fileWithPreview: FileWithPreview = Object.assign( new File([blob], "voiceNote.webm", { type: "audio/webm" }), { preview: url } ); // Add to state 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("Tus Upload : ", 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-expert/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); // } else if (fileTypeId == "2") { // setIsVideoUploadFinish(true); // } // if (fileTypeId == "3") { // setIsTextUploadFinish(true); // } // if (fileTypeId == "4") { // setIsAudioUploadFinish(true); // } // }, // }); // upload.start(); // } // function uploadResumableFile( // idx: number, // id: string, // file: any, // fileTypeId: string, // duration: string // ) { // return new Promise(async (resolve, reject) => { // const resCsrf = await getCsrfToken(); // const csrfToken = resCsrf?.data?.token; // const upload = new Upload(file, { // endpoint: `${process.env.NEXT_PUBLIC_API}/assignment-expert/file/upload`, // headers: { "X-XSRF-TOKEN": csrfToken }, // retryDelays: [0, 3000, 6000, 12000], // chunkSize: 20000, // metadata: { // assignmentId: id, // filename: file.name, // contentType: file.type, // fileTypeId, // duration, // }, // onBeforeRequest(req) { // req.getUnderlyingObject().withCredentials = true; // }, // onError(err) { // console.error("Upload error:", err); // reject(err); // }, // onSuccess() { // console.log("Upload selesai:", file.name); // resolve(true); // }, // }); // upload.start(); // }); // } function uploadResumableFile( idx: number, id: string, file: File, fileTypeId: string, duration: string ) { return new Promise(async (resolve, reject) => { try { const resCsrf = await getCsrfToken(); const csrfToken = resCsrf?.data?.token; const upload = new Upload(file, { endpoint: `${process.env.NEXT_PUBLIC_API}/assignment-expert/file/upload`, headers: { "X-XSRF-TOKEN": csrfToken }, retryDelays: [0, 3000, 6000], chunkSize: 20000, metadata: { assignmentId: id, filename: file.name, contentType: file.type, fileTypeId, duration, }, onBeforeRequest(req) { req.getUnderlyingObject().withCredentials = true; }, onError(error) { reject(error); }, onSuccess() { resolve(true); }, }); upload.start(); } catch (err) { reject(err); } }); } useEffect(() => { successTodo(); }, [ isImageUploadFinish, isVideoUploadFinish, isAudioUploadFinish, isTextUploadFinish, ]); function successTodo() { if ( isImageUploadFinish && isVideoUploadFinish && isAudioUploadFinish && isTextUploadFinish ) { successSubmit("/in/contributor/task-ta"); } } 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}

)}
setTaskType(String(value))} className="flex flex-wrap gap-3" >
{!isMabesApprover && (
{userCompetencies?.map((item: any) => (
handleCompetencyChange(item.id)} />
))}
)} {!isMabesApprover && (
Daftar Tenaga Ahli
{listExpert?.map((expert: any) => (
))}
{checkedLevels.size > 0 && (
{Array.from(checkedLevels).map((expertId) => { const expert = listExpert?.find( (exp: any) => exp.id === expertId ); return expert ? (
{expert.fullname}
) : null; })}
)}
)}
( )} /> {errors.narration?.message && (

{errors.narration.message}

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

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

))} {isRecording &&

Recording... {timer} seconds remaining

}{" "}
{links.map((link, index) => (
handleLinkChange(index, e.target.value) } /> {links.length > 1 && ( )}
))}
); }