"use client"; "use client"; import React, { useEffect, 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 } from "next/navigation"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Textarea } from "@/components/ui/textarea"; import { Icon } from "@iconify/react/dist/iconify.js"; import { Link } from "@/i18n/routing"; import { loading } from "@/lib/swal"; import { id } from "date-fns/locale"; import { DetailTicket } from "../ticketing/info-lainnya-types"; import { Description } from "@radix-ui/react-toast"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { ChevronDownIcon } from "lucide-react"; import { getCookiesDecrypt } from "@/lib/utils"; import { getCuratorUser, getEscalationDiscussion, getTicketingDetail, getTicketingInternalDiscussion, saveEscalationDiscussion, saveTicketsQuestion } from "@/service/service/communication/communication"; import { getOperatorUser } from "@/service/service/management-user/management-user"; const taskSchema = z.object({ title: z.string().min(1, { message: "Judul diperlukan" }), description: z.string().min(2, { message: "Narasi Penugasan harus lebih dari 2 karakter.", }), }); type DiscussionItem = { id: string; username: string; message: string; createdAt: string; parentId?: string | null; }; export type replyDetail = { id: number; message: string; createdAt: string; messageFrom: { id: number; fullname: string; }; messageTo: { id: number; fullname: string; }; }; export default function FormQuestionsDetail() { const MySwal = withReactContent(Swal); const { id } = useParams() as { id: string }; const roleId = getCookiesDecrypt("urie"); const [detail, setDetail] = useState(); const [ticketReply, setTicketReply] = useState([]); const [replyVisible, setReplyVisible] = useState(false); const [listDiscussion, setListDiscussion] = useState([]); const [message, setMessage] = useState(""); const [replyMessage, setReplyMessage] = useState>({}); const [detailTickets, setDetailTickets] = useState(null); const [selectedPriority, setSelectedPriority] = useState(""); const [selectedStatus, setSelectedStatus] = useState(""); const [operatorOpt, setOperatorOpt] = useState< { id: string; label: string; value: string }[] >([]); const [curatorOpt, setCuratorOpt] = useState< { id: string; label: string; value: string; badge: string }[] >([]); const [selectedOperator, setSelectedOperator] = useState([]); const [selectedOperatorEscalation, setSelectedOperatorEscalation] = useState< string[] >([]); const { control, handleSubmit, reset, formState: { errors }, } = useForm({ resolver: zodResolver(taskSchema), }); // useEffect(() => { // async function initState() { // const response = await getQuestionTicket(id); // setDetail(response?.data?.data); // if (response?.data !== null) { // setDetailTickets(response?.data?.data); // } // if (detailTickets?.emergencyIssue) { // reset({ // title: detailTickets.emergencyIssue.title || "", // description: detailTickets.emergencyIssue.description || "", // }); // // setSelectedPriority(String(detailTickets.emergencyIssue.urgencyId)); // // setSelectedStatus(String(detailTickets.statusId)); // jika ada // } // } // initState(); // getTicketReply(); // }, [id, reset]); useEffect(() => { async function initState() { const response = await getTicketingDetail(id); const detail = response?.data?.data; setDetail(detail); setDetailTickets(detail); if (detail?.escalationTeams) { const teamIds = detail.escalationTeams .split(":") .filter((id: string) => id); setSelectedOperatorEscalation(teamIds); } getTicketReply(); } initState(); }, [id]); useEffect(() => { async function getOperator() { const res = await getOperatorUser(detailTickets?.typeId); if (res?.data !== null) { const rawUser = res?.data?.data; const optionArr = rawUser?.map((option: any) => ({ id: option.id, label: option.fullName, value: option.id.toString(), // pastikan string })); setOperatorOpt(optionArr); // 👇 Parse `assignedTeams` ke dalam array string if (detailTickets?.assignedTeams) { const assigned = detailTickets.assignedTeams .split(":") .filter((id: string) => id); // hapus string kosong setSelectedOperator(assigned); } } } getOperator(); }, [detailTickets]); useEffect(() => { async function getCurator() { const res = await getCuratorUser(); const rawUser = res?.data?.data?.content ?? []; // ✅ langsung ambil dari content const optionArr = rawUser?.map((option: any) => ({ id: option.id, label: `${option.username} | ${option.fullname}`, value: option.id.toString(), badge: option.userLevel?.name ?? "", // optional jika ingin tampilkan badge/tingkatan })); setCuratorOpt(optionArr); } getCurator(); }, []); async function getTicketReply() { const res = await getTicketingInternalDiscussion(id); if (res?.data !== null) { setTicketReply(res?.data?.data); } } const onSubmit = async (data: any) => { try { const payload = { id, title: data.title, description: data.description, priorityId: selectedPriority, statusId: selectedStatus, typeId: detailTickets?.typeId, parentCommentId: detailTickets?.feedId, }; const response = await saveTicketsQuestion(payload); MySwal.fire({ title: "Sukses", text: "Data berhasil diperbarui.", icon: "success", }); // Refresh data jika perlu getTicketReply(); } catch (error) { console.error("Gagal update:", error); MySwal.fire({ title: "Error", text: "Terjadi kesalahan saat memperbarui.", icon: "error", }); } }; // const handleSendReply = () => { // if (replyMessage.trim() === "") return; // const newReply = { // id: replies.length + 1, // name: "Mabes Polri - Approver", // Sesuaikan dengan data dinamis jika ada // message: replyMessage, // timestamp: new Date().toISOString().slice(0, 19).replace("T", " "), // }; // setReplies([...replies, newReply]); // setReplyMessage(""); // }; useEffect(() => { fetchDiscussions(); }, [id]); const fetchDiscussions = async () => { try { const response = await getEscalationDiscussion(id); setListDiscussion(response?.data?.data || []); } catch (error) { console.error("Gagal mengambil diskusi", error); } }; const sendDiscussionParent = async () => { if (message?.trim().length === 0) return; const data = { ticketId: id, message, parentId: null, }; try { await saveEscalationDiscussion(data); setMessage(""); const response = await getEscalationDiscussion(id); setListDiscussion(response?.data?.data || []); } catch (error) { console.error("Gagal kirim tanggapan", error); } }; const sendDiscussionChild = async (parentId: string) => { const inputMsg = replyMessage[parentId]; if (!inputMsg || inputMsg.trim().length === 0) return; const data = { ticketId: id, message: inputMsg, parentMessageId: parentId, }; try { await saveEscalationDiscussion(data); const response = await getEscalationDiscussion(id); setListDiscussion(response?.data?.data || []); setReplyMessage((prev) => ({ ...prev, [parentId]: "" })); } catch (error) { console.error("Gagal kirim balasan", error); } }; return (
{detail !== undefined && (

Ticket #{detail.id}

{detail?.commentFromUserName} {` `} mengirimkan pesan untuk{` `} {detail?.message}

{`${new Date(detail?.createdAt).getDate()}-${ new Date(detail?.createdAt).getMonth() + 1 }-${new Date(detail?.createdAt).getFullYear()} ${new Date( detail?.createdAt ).getHours()}:${new Date(detail?.createdAt).getMinutes()}`}

{detail.message}

)}
{detail !== undefined && (
( )} /> {/* {errors.title?.message && (

{errors.title.message}

)} */}
{(roleId === "9" || roleId === "10") && (
{/* Tag yang ditampilkan secara kolom */} {selectedOperator.length > 0 && (
{selectedOperator.map((id) => { const label = operatorOpt.find( (op: any) => op.value === id )?.label; return (
{label}
); })}
)} {/* Popover Checkbox Dropdown */}
{operatorOpt.map((op: any) => ( ))}
)}
(