mediahub-fe/app/[locale]/(protected)/contributor/agenda-setting/event-modal.tsx

599 lines
22 KiB
TypeScript
Raw Normal View History

// "use client";
2024-11-27 04:14:10 +00:00
import React, { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useForm, Controller } from "react-hook-form";
2024-12-10 07:12:18 +00:00
import { cn } from "@/lib/utils";
import { format } from "date-fns";
2024-11-27 04:14:10 +00:00
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Calendar } from "@/components/ui/calendar";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
2024-12-30 13:43:39 +00:00
import { Loader2, CalendarIcon, ChevronUp, ChevronDown } from "lucide-react";
2024-11-27 04:14:10 +00:00
import DeleteConfirmationDialog from "@/components/delete-confirmation-dialog";
import { CalendarCategory } from "./data";
2024-12-10 07:12:18 +00:00
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
2024-12-30 13:43:39 +00:00
DialogTrigger,
2024-12-10 07:12:18 +00:00
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { error, loading } from "@/lib/swal";
import Cookies from "js-cookie";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useRouter } from "next/navigation";
import { postSchedule } from "@/service/schedule/schedule";
import { saveAgendaSettings } from "@/service/agenda-setting/agenda-setting";
2024-12-30 13:43:39 +00:00
import { Checkbox } from "@/components/ui/checkbox";
import { getUserLevelForAssignments } from "@/service/task";
import { AudioRecorder } from "react-audio-voice-recorder";
2024-11-27 04:14:10 +00:00
const schema = z.object({
title: z.string().min(3, { message: "Required" }),
description: z.string().min(3, { message: "Required" }),
2024-11-27 04:14:10 +00:00
});
2024-12-10 07:12:18 +00:00
const EventModal = ({
open,
onClose,
categories,
event,
selectedDate,
}: {
2024-11-27 04:14:10 +00:00
open: boolean;
onClose: () => void;
categories: any;
event: any;
2024-12-10 07:12:18 +00:00
selectedDate: any;
2024-11-27 04:14:10 +00:00
}) => {
const [startDate, setStartDate] = useState<Date>(new Date());
const [endDate, setEndDate] = useState<Date>(new Date());
const [isPending, startTransition] = React.useTransition();
2024-12-10 07:12:18 +00:00
const [calendarProps, setCalendarProps] = React.useState<any>(
categories[0].value
);
2024-12-30 13:43:39 +00:00
const [listDest, setListDest] = useState([]);
2024-11-27 04:14:10 +00:00
const [deleteModalOpen, setDeleteModalOpen] = useState<boolean>(false);
const [eventIdToDelete, setEventIdToDelete] = useState<string | null>(null);
const MySwal = withReactContent(Swal);
const router = useRouter();
2024-12-30 13:43:39 +00:00
const [isLoading, setIsLoading] = useState(false);
const [checkedLevels, setCheckedLevels] = useState(new Set());
const [expandedPolda, setExpandedPolda] = useState([{}]);
const [audioFile, setAudioFile] = useState<File | null>(null);
const [isRecording, setIsRecording] = useState(false);
const [timer, setTimer] = useState<number>(120);
2024-11-27 04:14:10 +00:00
const {
register,
control,
reset,
setValue,
formState: { errors },
handleSubmit,
} = useForm({
resolver: zodResolver(schema),
mode: "all",
});
2024-12-30 13:43:39 +00:00
useEffect(() => {
async function fetchPoldaPolres() {
setIsLoading(true);
try {
const response = await getUserLevelForAssignments();
setListDest(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 save = async (data: any) => {
2024-12-30 13:43:39 +00:00
if (!audioFile) return;
const formData = new FormData();
formData.append("voiceNote", audioFile);
const reqData = {
title: data.title,
2025-01-01 08:33:42 +00:00
description: data.description,
agendaType: calendarProps,
startDate: format(startDate, "yyyy-MM-dd"),
endDate: format(endDate, "yyyy-MM-dd"),
2024-12-30 13:43:39 +00:00
voiceNote: formData,
};
console.log("Submitted Data:", reqData);
const response = await saveAgendaSettings(reqData);
if (response.error) {
error(response.message);
return false;
}
Cookies.set("AgendaSetting", response.data.data.id, {
expires: 1,
});
// Optional: Use Swal for success feedback
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
2025-01-01 08:33:42 +00:00
router.push("en/contributor/agenda-setting");
2024-11-27 04:14:10 +00:00
});
};
const onSubmit = (data: any) => {
save(data);
};
2024-11-27 04:14:10 +00:00
useEffect(() => {
if (selectedDate) {
setStartDate(selectedDate.date);
setEndDate(selectedDate.date);
}
if (event) {
setStartDate(event?.event?.start);
setEndDate(event?.event?.end);
const eventCalendar = event?.event?.extendedProps?.calendar;
setCalendarProps(eventCalendar || categories[0].value);
2024-11-27 04:14:10 +00:00
}
setValue("title", event?.event?.title || "");
setValue("description", event?.event?.description || "");
2024-11-27 04:14:10 +00:00
}, [event, selectedDate, open, categories, setValue]);
const onDeleteEventAction = async () => {
try {
2024-12-10 07:12:18 +00:00
} catch (error) {}
2024-11-27 04:14:10 +00:00
};
const handleOpenDeleteModal = (eventId: string) => {
setEventIdToDelete(eventId);
setDeleteModalOpen(true);
onClose();
};
2024-12-30 13:43:39 +00:00
const toggleExpand = (poldaId: any) => {
setExpandedPolda((prev: any) => ({
...prev,
[poldaId]: !prev[poldaId],
}));
};
const onRecordingStart = () => {
setIsRecording(true);
// Start a timer that stops the recording after 2 minutes (120 seconds)
const countdown = setInterval(() => {
setTimer((prevTimer) => {
if (prevTimer <= 1) {
clearInterval(countdown); // Stop the timer when it reaches 0
return 0;
}
return prevTimer - 1;
});
}, 1000); // Update every second
// Automatically stop recording after 2 minutes
setTimeout(() => {
if (isRecording) {
handleStopRecording();
}
}, 120000); // Stop after 2 minutes (120,000 ms)
};
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
const file = new File([blob], "voiceNote.webm", { type: "audio/webm" });
setAudioFile(file);
};
const handleDeleteAudio = () => {
// Remove the audio file by setting state to null
setAudioFile(null);
const audioElements = document.querySelectorAll("audio");
audioElements.forEach((audio) => audio.remove());
};
2024-11-27 04:14:10 +00:00
return (
<>
<DeleteConfirmationDialog
open={deleteModalOpen}
onClose={() => setDeleteModalOpen(false)}
onConfirm={onDeleteEventAction}
defaultToast={false}
/>
<Dialog open={open} onOpenChange={onClose}>
2024-12-30 13:43:39 +00:00
<DialogContent
onPointerDownOutside={onClose}
className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[700px] max-h-[80vh] overflow-y-auto"
>
2024-11-27 04:14:10 +00:00
<DialogHeader>
<DialogTitle>
{event ? "Edit Agenda Setting" : "Create Agenda Setting"}{" "}
{event?.title}
2024-11-27 04:14:10 +00:00
</DialogTitle>
</DialogHeader>
2024-12-30 13:43:39 +00:00
<div className="mt-6 h-full ">
2024-11-27 04:14:10 +00:00
<form className="h-full" onSubmit={handleSubmit(onSubmit)}>
<div className="space-y-4 pb-5 ">
<div className="space-y-1.5">
<Label htmlFor="title">Judul Agenda</Label>
2025-01-01 08:33:42 +00:00
<Controller
control={control}
name="title"
render={({ field }) => (
<Input
size="md"
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Enter Title"
/>
)}
2024-11-27 04:14:10 +00:00
/>
{errors?.title?.message && (
<div className="text-destructive text-sm">
2024-12-10 07:12:18 +00:00
{typeof errors?.title?.message === "string"
2024-11-27 04:14:10 +00:00
? errors?.title?.message
: JSON.stringify(errors?.title?.message)}
</div>
)}
</div>
<div className="space-y-1.5">
<Label htmlFor="startDate">Start Date </Label>
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
size="md"
className={cn(
"w-full justify-between text-left font-normal border-default-200 text-default-600 md:px-4",
!startDate && "text-muted-foreground"
)}
>
{startDate ? (
format(startDate, "PP")
) : (
<span>Pick a date</span>
)}
<CalendarIcon className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Controller
name="startDate"
control={control}
render={({ field }) => (
<Calendar
mode="single"
selected={startDate}
onSelect={(date) => setStartDate(date as Date)}
initialFocus
/>
)}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-1.5">
<Label htmlFor="endDate">End Date</Label>
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
size="md"
className={cn(
"w-full justify-between text-left font-normal border-default-200 text-default-600 md:px-4",
!endDate && "text-muted-foreground"
)}
>
{endDate ? (
format(endDate, "PP")
) : (
<span>Pick a date</span>
)}
<CalendarIcon className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Controller
name="endDate"
control={control}
render={({ field }) => (
<Calendar
mode="single"
selected={endDate}
onSelect={(date) => setEndDate(date as Date)}
initialFocus
/>
)}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-1.5">
<Label htmlFor="calendarProps">Jenis Agenda </Label>
2024-11-27 04:14:10 +00:00
<Controller
name="calendarProps"
control={control}
render={({ field }) => (
<Select
value={calendarProps}
onValueChange={(data) => setCalendarProps(data)}
>
<SelectTrigger>
<SelectValue placeholder="Label" />
</SelectTrigger>
<SelectContent>
{categories.map((category: CalendarCategory) => (
<SelectItem
value={category.value}
key={category.value}
>
{category.label}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</div>
2024-12-30 13:43:39 +00:00
{calendarProps === "polda" && (
<div>
<Dialog>
<DialogTrigger asChild>
<Button variant="soft" size="sm" color="primary">
[Kustom]
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[1500px]">
<DialogHeader>
<DialogTitle>
Daftar Wilayah Polda dan Polres
</DialogTitle>
</DialogHeader>
<div className="grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto">
{listDest.map((polda: any) => (
<div key={polda.id} className="border p-2">
<Label className="flex items-center">
<Checkbox
checked={checkedLevels.has(polda.id)}
onCheckedChange={() =>
handleCheckboxChange(polda.id)
}
className="mr-3"
/>
{polda.name}
<button
onClick={() => toggleExpand(polda.id)}
className="ml-2 focus:outline-none"
>
{expandedPolda[polda.id] ? (
<ChevronUp size={16} />
) : (
<ChevronDown size={16} />
)}
</button>
</Label>
{expandedPolda[polda.id] && (
<div className="ml-6 mt-2">
<Label className="block">
<Checkbox
checked={polda?.subDestination?.every(
(polres: any) =>
checkedLevels.has(polres.id)
)}
onCheckedChange={(isChecked) => {
const updatedLevels = new Set(
checkedLevels
);
polda?.subDestination?.forEach(
(polres: any) => {
if (isChecked) {
updatedLevels.add(polres.id);
} else {
updatedLevels.delete(polres.id);
}
}
);
setCheckedLevels(updatedLevels);
}}
className="mr-2"
/>
Pilih Semua Polres
</Label>
{polda?.subDestination?.map((polres: any) => (
<Label
key={polres.id}
className="block mt-1"
>
<Checkbox
checked={checkedLevels.has(polres.id)}
onCheckedChange={() =>
handleCheckboxChange(polres.id)
}
className="mr-2"
/>
{polres.name}
</Label>
))}
</div>
)}
</div>
))}
</div>
</DialogContent>
</Dialog>
</div>
)}
<div className="space-y-1.5">
<Label htmlFor="description">Isi Agenda Setting</Label>
2025-01-01 08:33:42 +00:00
<Controller
control={control}
name="description"
render={({ field }) => (
<Textarea
defaultValue={field.value}
onChange={field.onChange}
placeholder="Enter Title"
/>
)}
/>
{errors?.description?.message && (
<div className="text-destructive text-sm">
{typeof errors?.description?.message === "string"
? errors?.description?.message
: JSON.stringify(errors?.description?.message)}
</div>
)}
</div>
2024-12-30 13:43:39 +00:00
<div className="space-y-1.5">
<Label htmlFor="attachments">Lampiran</Label>
<div className="space-y-3">
<div>
<Label>Video</Label>
<Input
type="file"
accept="video/*"
multiple
{...register("attachments.video")}
/>
</div>
<div>
<Label>Foto</Label>
<Input
type="file"
accept="image/*"
multiple
{...register("attachments.photo")}
/>
</div>
<div>
<Label>Teks</Label>
<Input
type="file"
accept="text/plain"
multiple
{...register("attachments.text")}
/>
</div>
<div>
<Label>Voice Note</Label>
<AudioRecorder
onRecordingComplete={addAudioElement}
audioTrackConstraints={{
noiseSuppression: true,
echoCancellation: true,
}}
downloadOnSavePress={true}
downloadFileExtension="webm"
/>
</div>
{audioFile && (
<div className="flex flex-row justify-between items-center">
<p>Voice note ready to submit: {audioFile.name}</p>
<Button
type="button"
onClick={handleDeleteAudio}
size="sm"
color="destructive"
>
X
</Button>
</div>
)}
{isRecording && (
<p>Recording... {timer} seconds remaining</p>
)}{" "}
{/* Display remaining time */}
</div>
</div>
2024-11-27 04:14:10 +00:00
</div>
<div className="flex flex-wrap gap-2 mt-10">
<Button type="submit" disabled={isPending} className="flex-1">
{isPending ? (
<>
<Loader2 className="me-2 h-4 w-4 animate-spin" />
{event ? "Updating..." : "Adding..."}
</>
) : event ? (
"Update Agenda Setting"
2024-11-27 04:14:10 +00:00
) : (
"Simpan Agenda Setting"
2024-11-27 04:14:10 +00:00
)}
</Button>
{event && (
<Button
type="button"
color="destructive"
onClick={() => handleOpenDeleteModal(event?.event?.id)}
className="flex-1"
>
Delete
</Button>
)}
</div>
</form>
</div>
</DialogContent>
</Dialog>
</>
);
};
export default EventModal;