mediahub-fe/components/form/account-report/account-report-form.tsx

393 lines
12 KiB
TypeScript
Raw Normal View History

"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,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import JoditEditor from "jodit-react";
import {
createTask,
createTaskTa,
getTask,
getUserLevelForAssignments,
} from "@/service/task";
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 { 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 { detailMedia } from "@/service/curated-content/curated-content";
import { Textarea } from "@/components/ui/textarea";
import { FormLabel } from "@/components/ui/form";
import { getUserReports, saveUserReportsAction } from "@/service/report/report";
import { postBlog } from "@/service/blog/blog";
import { Link } from "@/i18n/routing";
const reportSchema = z.object({
reportedBy: z.string().min(1, { message: "Judul diperlukan" }),
user: z.string().min(1, { message: "Judul diperlukan" }),
message: 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 reportDetail = {
id: number;
message: string;
reportedBy: {
id: number;
fullname: string;
};
user: {
id: number;
fullname: string;
};
};
const CustomEditor = dynamic(
() => {
return import("@/components/editor/custom-editor");
},
{ ssr: false }
);
export default function FormAccountReport() {
const MySwal = withReactContent(Swal);
const router = useRouter();
const editor = useRef(null);
type ReportSchema = z.infer<typeof reportSchema>;
const { id } = useParams() as { id: string };
console.log(id);
// State for various form fields
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 [assignmentType, setAssignmentType] = useState("mediahub");
// const [assignmentCategory, setAssignmentCategory] = useState("publication");
const [mainType, setMainType] = useState<string>("1");
const [taskType, setTaskType] = useState<string>("atensi-khusus");
const [broadcastType, setBroadcastType] = useState<string>("");
const [type, setType] = useState<string>("1");
const [selectedTarget, setSelectedTarget] = useState("3,4");
const [detail, setDetail] = useState<reportDetail>();
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<File | null>(null);
const [isRecording, setIsRecording] = useState(false);
const [timer, setTimer] = useState<number>(120);
const t = useTranslations("Form");
const [imageFiles, setImageFiles] = useState<FileWithPreview[]>([]);
const [videoFiles, setVideoFiles] = useState<FileWithPreview[]>([]);
const [textFiles, setTextFiles] = useState<FileWithPreview[]>([]);
const [audioFiles, setAudioFiles] = useState<FileWithPreview[]>([]);
const [isImageUploadFinish, setIsImageUploadFinish] = useState(false);
const [isVideoUploadFinish, setIsVideoUploadFinish] = useState(false);
const [isTextUploadFinish, setIsTextUploadFinish] = useState(false);
const [isAudioUploadFinish, setIsAudioUploadFinish] = useState(false);
const [voiceNoteLink, setVoiceNoteLink] = useState("");
2025-06-07 12:37:06 +00:00
const [date, setDate] = React.useState<DateRange | undefined>();
const [platformTypeVisible, setPlatformTypeVisible] = useState(false);
const [unitSelection, setUnitSelection] = useState({
semua: false,
mabes: false,
polda: false,
polres: false,
satker: false,
});
const [taskOutput, setTaskOutput] = useState({
all: false,
video: false,
audio: false,
image: false,
text: false,
});
const [links, setLinks] = useState<string[]>([""]);
const {
register,
control,
setValue,
handleSubmit,
formState: { errors },
} = useForm<ReportSchema>({
resolver: zodResolver(reportSchema),
mode: "all",
});
// const handleRadioChange = (event: React.ChangeEvent<HTMLInputElement>) => {
// 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 handleUnitChange = (
key: keyof typeof unitSelection,
value: boolean
) => {
if (key === "semua") {
const newState = {
semua: value,
mabes: value,
polda: value,
polres: value,
satker: value,
};
setUnitSelection(newState);
} else {
const updatedSelection = {
...unitSelection,
[key]: value,
};
const allChecked = ["mabes", "polda", "polres", "satker"].every(
(k) => updatedSelection[k as keyof typeof unitSelection]
);
updatedSelection.semua = allChecked;
setUnitSelection(updatedSelection);
}
};
useEffect(() => {
async function getReportData() {
if (id != undefined) {
const res = await getUserReports(id);
close();
if (res?.data?.data != undefined) {
const data = res?.data?.data;
console.log("Data :", data);
setDetail(data);
}
}
}
getReportData();
}, [id]);
const save = async (data: ReportSchema) => {
loading();
const requestData = {
...data,
id: detail?.id,
action: selectedTarget,
};
const response = await saveUserReportsAction(id, requestData);
console.log("Form Data Submitted:", requestData);
console.log("response", response);
if (response?.error) {
MySwal.fire("Error", response?.message, "error");
return;
}
close();
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push("/in/contributor/blog");
});
};
const onSubmit = (data: ReportSchema) => {
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);
}
});
};
return (
<Card>
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">{t("form-task")}</p>
{detail !== undefined ? (
<form onSubmit={handleSubmit(onSubmit)}>
<div className="flex flex-col justify-center items-center gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2 w-6/12">
<Label>Pelapor</Label>
<Controller
control={control}
name="reportedBy"
render={({ field }) => (
<Input
size="md"
type="text"
defaultValue={detail?.reportedBy?.fullname}
onChange={field.onChange}
placeholder="Enter Title"
/>
)}
/>
{errors.reportedBy?.message && (
<p className="text-red-400 text-sm">
{errors.reportedBy.message}
</p>
)}
</div>
<div className="space-y-2 mt-3 w-6/12">
<Label>Terlapor</Label>
<Controller
control={control}
name="user"
render={({ field }) => (
<Input
size="md"
type="text"
defaultValue={detail?.user?.fullname}
onChange={field.onChange}
placeholder="Enter Title"
/>
)}
/>
{errors.user?.message && (
<p className="text-red-400 text-sm">{errors.user.message}</p>
)}
</div>
<div className="mt-3 space-y-2 w-6/12">
<Label>Alasan Report</Label>
<Controller
control={control}
name="message"
render={({ field: { onChange, value } }) => (
<Textarea
defaultValue={detail?.message}
placeholder="Enter Title"
/>
)}
/>
{errors.message?.message && (
<p className="text-red-400 text-sm">
{errors.message.message}
</p>
)}
</div>
<div className="mt-3 space-y-2 w-6/12">
<Select>
<Label>
Status<span className="text-red-600">*</span>
</Label>
<SelectTrigger size="md">
<SelectValue placeholder="Select" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel>Pilih Tindakan</SelectLabel>
<SelectItem value="pending">Pending</SelectItem>
<SelectItem value="suspended">Suspended</SelectItem>
<SelectItem value="rejected">Rejected</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</div>
</div>
<div className="flex flex-row gap-3 justify-end">
<div className="mt-4">
<Link href={"/supervisor/communications/account-report"}>
<Button variant={"outline"} color="primary">
{t("cancel")}
</Button>
</Link>
</div>
<div className="mt-4">
<Button type="submit" color="primary">
{t("submit")}
</Button>
</div>
</div>
</form>
) : (
""
)}
</div>
</Card>
);
}