"use client";
import React, { useState, useEffect, useRef, Fragment } 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";
import { cn, getCookiesDecrypt } from "@/lib/utils";
import { format, isDate } from "date-fns";
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";
import {
  Loader2,
  CalendarIcon,
  ChevronUp,
  ChevronDown,
  Music,
} from "lucide-react";
import { DateRange } from "react-day-picker";
import DeleteConfirmationDialog from "@/components/delete-confirmation-dialog";
import { CalendarCategory } from "./data";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { error, loading, success } from "@/lib/swal";
import Cookies from "js-cookie";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { postSchedule } from "@/service/schedule/schedule";
import {
  deleteAgendaSettings,
  getAgendaSettingsById,
  publishAgendaSettings,
  saveAgendaSettings,
} from "@/service/agenda-setting/agenda-setting";
import { Checkbox } from "@/components/ui/checkbox";
import { getUserLevelForAssignments } from "@/service/task";
import { AudioRecorder } from "react-audio-voice-recorder";
import FileUploader from "@/components/form/shared/file-uploader";
import { Upload } from "tus-js-client";
import { getCsrfToken } from "@/service/auth";
import { Icon } from "@iconify/react";
import Image from "next/image";
import { UnitMapping } from "./unit-mapping";
import { useToast } from "@/components/ui/use-toast";
import { usePathname, useRouter } from "next/navigation";
import { Card } from "@/components/ui/card";
import WavesurferPlayer from "@wavesurfer/react";
import WaveSurfer from "wavesurfer.js";

const schema = z.object({
  title: z.string().min(3, { message: "Required" }),
  description: z
    .string()
    .min(2, { message: "Narasi Penugasan harus lebih dari 2 karakter." }),
});

interface FileWithPreview extends File {
  preview: string;
}

interface FileUploaded {
  id: number;
  url: string;
}

const EventModal = ({
  open,
  onClose,
  categories,
  event,
  selectedDate,
}: {
  open: boolean;
  onClose: () => void;
  categories: any;
  event: any;
  selectedDate: any;
}) => {
  const roleId = Number(getCookiesDecrypt("urie")) || 0;
  const [detail, setDetail] = useState<any>();
  const [date, setDate] = React.useState<DateRange | undefined>({
    from: new Date(),
    to: new Date(),
  });
  const [isPending, startTransition] = React.useTransition();
  const [listDest, setListDest] = useState([]);
  const [deleteModalOpen, setDeleteModalOpen] = useState<boolean>(false);
  const [eventIdToDelete, setEventIdToDelete] = useState<string | null>(null);
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const pathname = usePathname();
  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);
  const [detailData, setDetailData] = useState<any>();
  const [imageFiles, setImageFiles] = useState<FileWithPreview[]>([]);
  const [videoFiles, setVideoFiles] = useState<FileWithPreview[]>([]);
  const [textFiles, setTextFiles] = useState<FileWithPreview[]>([]);
  const [audioFiles, setAudioFiles] = useState<FileWithPreview[]>([]);
  const [imageUploadedFiles, setImageUploadedFiles] = useState<FileUploaded[]>(
    []
  );
  const [videoUploadedFiles, setVideoUploadedFiles] = useState<FileUploaded[]>(
    []
  );
  const [textUploadedFiles, setTextUploadedFiles] = useState<FileUploaded[]>(
    []
  );
  const [audioUploadedFiles, setAudioUploadedFiles] = useState<FileUploaded[]>(
    []
  );
  const { toast } = useToast();
  const [isImageUploadFinish, setIsImageUploadFinish] = useState(false);
  const [isVideoUploadFinish, setIsVideoUploadFinish] = useState(false);
  const [isTextUploadFinish, setIsTextUploadFinish] = useState(false);
  const [isAudioUploadFinish, setIsAudioUploadFinish] = useState(false);
  const [unitData, setUnitData] = useState<string[]>([]);
  const [satkerData, setSatkerData] = useState<string[]>([]);
  let progressInfo: any = [];
  let counterUpdateProgress = 0;
  const [progressList, setProgressList] = useState<any>([]);
  let uploadPersen = 0;
  const [isStartUpload, setIsStartUpload] = useState(false);
  const [counterProgress, setCounterProgress] = useState(0);
  const [wilayahPublish, setWilayahPublish] = React.useState({
    semua: false,
    nasional: false,
    polda: false,
    polres: false,
    satker: false,
    international: false,
  });

  const [agendaType, setAgendaType] = React.useState(""); // State untuk agendaType
  const [selectedPolda, setSelectedPolda] = useState<string[]>([]);
  const [selectedPolres, setSelectedPolres] = useState<string[]>([]);
  const [selectedSatker, setSelectedSatker] = useState<string[]>([]);
  const isDetailMode = true;
  const [wavesurfer, setWavesurfer] = useState<WaveSurfer>();
  const [isPlaying, setIsPlaying] = useState(false);
  const [isPublishing, setIsPublishing] = useState(false);
  const [isDatePickerOpen, setIsDatePickerOpen] = useState(false);

  const {
    register,
    control,
    reset,
    setValue,
    formState: { errors },
    handleSubmit,
  } = useForm({
    resolver: zodResolver(schema),
    mode: "all",
  });

  useEffect(() => {
    async function fetchDetailData() {
      const res = await getAgendaSettingsById(event?.event?.id);
      const detail = res?.data?.data;
      setDetailData(detail);

      const description = detail?.description;
      if (description) {
        setValue("description", description);
      }

      const attachments = detail?.attachments;
      setImageUploadedFiles(
        attachments?.filter((file: any) => file.fileTypeId == 1)
      );
      setVideoUploadedFiles(
        attachments?.filter((file: any) => file.fileTypeId == 2)
      );
      setTextUploadedFiles(
        attachments?.filter((file: any) => file.fileTypeId == 3)
      );
      setAudioUploadedFiles(
        attachments?.filter((file: any) => file.fileTypeId == 4)
      );

      const rawAgendaTypes = detail?.agendaType?.split(",") || []; // ["0","1","2","3","4","5"]
      const assignedToLevel = detail?.assignedToLevel?.split(",") || [];

      const wilayahState = {
        semua: false,
        nasional: false,
        polda: false,
        polres: false,
        satker: false,
        international: false,
      };

      rawAgendaTypes.forEach((type: any) => {
        switch (type) {
          case "0":
            wilayahState.semua = true;
            break;
          case "1":
            wilayahState.nasional = true;
            break;
          case "2":
            wilayahState.polda = true;
            break;
          case "3":
            wilayahState.polres = true;
            break;
          case "4":
            wilayahState.satker = true;
            break;
          case "5":
            wilayahState.international = true;
            break;
          default:
            break;
        }
      });

      setWilayahPublish(wilayahState);

      if (rawAgendaTypes.includes("2")) {
        setSelectedPolda(assignedToLevel);
      }
      if (rawAgendaTypes.includes("3")) {
        setSelectedPolres(assignedToLevel);
      }
      if (rawAgendaTypes.includes("4")) {
        setSelectedSatker(assignedToLevel);
      }
    }
    fetchDetailData();
  }, [event, setValue]);

  useEffect(() => {
    setIsDatePickerOpen(false);
  }, [onClose])

  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 wilayahValueMap: Record<string, string> = {
    semua: "0",
    nasional: "1",
    polda: "2",
    polres: "3",
    satker: "4",
    international: "5",
  };

  const toggleWilayah = (key: string) => {
    setWilayahPublish((prev: any) => {
      let newState = { ...prev };
      if (key === "semua") {
        const newChecked = !prev.semua;
        newState = {
          semua: newChecked,
          nasional: newChecked,
          polda: newChecked,
          polres: newChecked,
          satker: newChecked,
          international: newChecked,
        };

        if (newChecked) {
          setAgendaType("0,1,2,3,4,5");
        } else {
          setAgendaType("");
        }

        return newState;
      }

      newState[key] = !prev[key];
      newState.semua = false;

      const selectedKeys = Object.entries(newState)
        .filter(([k, v]) => v && k !== "semua")
        .map(([k]) => wilayahValueMap[k]);

      setAgendaType(selectedKeys.join(","));

      return newState;
    });
  };

  const save = async (data: any, publish = false) => {
    const agendaTypeList: string[] = [];
    const assignedToLevelList: string[] = [];

    // // Mapping dari checkbox wilayah ke agendaType
    // Object.keys(wilayahPublish).forEach((key) => {
    //   if (wilayahPublish[key as keyof typeof wilayahPublish]) {
    //     agendaTypeList.push(wilayahValueMap[key]);
    //   }
    // });

    if (wilayahPublish.semua) {
      agendaTypeList.push("0", "1", "2", "3", "4", "5");
    } else {
      Object.keys(wilayahPublish).forEach((key) => {
        if (
          wilayahPublish[key as keyof typeof wilayahPublish] &&
          key !== "semua"
        ) {
          agendaTypeList.push(wilayahValueMap[key]);
        }
      });
    }

    // Unit-unit berdasarkan wilayah yang aktif
    if (wilayahPublish.polda && selectedPolda.length > 0) {
      assignedToLevelList.push(...selectedPolda);
    }
    if (wilayahPublish.polres && selectedPolres.length > 0) {
      assignedToLevelList.push(...selectedPolres);
    }
    if (wilayahPublish.satker && selectedSatker.length > 0) {
      assignedToLevelList.push(...selectedSatker);
    }

    const reqData = {
      id: detailData?.id,
      title: data.title,
      description: data.description,
      agendaType: agendaTypeList.join(","), 
      assignedToLevel: assignedToLevelList.join(","), 
      startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
      endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
    };

    // console.log("Submitted Data:", reqData);

    const response = await saveAgendaSettings(reqData);
    if (response?.error) {
      error(response?.message);
      return false;
    }

    const id = response?.data?.data?.id;

    loading();
    if (imageFiles?.length === 0) {
      setIsImageUploadFinish(true);
    }
    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, 
        "4",
        "0" 
      );
    });
    if (publish) {
      setIsPublishing(true);
      const publishResponse = await publishAgendaSettings(id);
      setIsPublishing(false);

      if (publishResponse?.error) {
        error(publishResponse?.message);
        return false;
      }

      success("Agenda berhasil dipublikasikan!");
    }
  };

  const onSubmit = (data: any) => {
    if (
      (wilayahPublish.polda && selectedPolda.length === 0) ||
      (wilayahPublish.satker && selectedSatker.length === 0) ||
      (wilayahPublish.polres && selectedPolres.length === 0)
    ) {
      toast({
        title: "Pilih ID untuk Polda/Satker",
        variant: "destructive",
      });
      return;
    }
    save(data);
  };

  useEffect(() => {
    // console.log("Event data:", event);
    // console.log("Selected date:", selectedDate);
    
    if (selectedDate) {
      setDate({
        from: selectedDate.date,
        to: selectedDate.date,
      });
    }
    if (event) {
      setDate({
        from: event?.event?.start,
        to: event?.event?.end,
      });
      const eventCalendar = event?.event?.extendedProps?.calendar;
      setAgendaType(
        eventCalendar || (categories?.length > 0 && categories[0].value)
      );
    }
    setValue("title", event?.event?.title || "");
    setValue("description", event?.event?.description || "");
  }, [event, selectedDate, open, categories, setValue]);

  const onDeleteEventAction = async () => {
    try {
    } catch (error) {}
  };

  const handleOpenDeleteModal = (eventId: string) => {
    setEventIdToDelete(eventId);
    setDeleteModalOpen(true);
    onClose();
  };

  const toggleExpand = (poldaId: any) => {
    // console.log("Toogle : ", expandedPolda);
    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 = () => {
    setAudioFile(null);
    const audioElements = document.querySelectorAll("audio");
    audioElements.forEach((audio) => audio.remove());
  };

  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}/agenda-settings/file/upload`,
      headers: headers,
      retryDelays: [0, 3000, 6000, 12_000, 24_000],
      chunkSize: 20_000,
      metadata: {
        agendaSettingId: 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();
  }

  useEffect(() => {
    successTodo();
  }, [
    isImageUploadFinish,
    isVideoUploadFinish,
    isAudioUploadFinish,
    isTextUploadFinish,
  ]);

  function successTodo() {
    if (
      isImageUploadFinish &&
      isVideoUploadFinish &&
      isAudioUploadFinish &&
      isTextUploadFinish
    ) {
      successSubmit("/in/contributor/agenda-setting");
    }
  }

  const successSubmit = (redirect: string) => {
    MySwal.fire({
      title: "Sukses",
      text: "Data berhasil disimpan.",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then(() => {
      router.push(redirect);
      window.location.reload();
    });
  };

  const renderFilePreview = (url: string) => {
    return (
      <Image
        width={48}
        height={48}
        alt={"file preview"}
        src={url}
        className=" rounded border p-0.5"
      />
    );
  };

  const handleRemoveFile = (id: number) => {};

  async function doDelete(id: any) {
    loading();
    const resDelete = await deleteAgendaSettings(id);
    if (resDelete?.error) {
      error(resDelete.message);
      return false;
    }
    close();
    successSubmitDelete("/in/contributor/agenda-setting");
    window.location.reload();
  }

  const handleDelete = (id: any) => {
    MySwal.fire({
      title: "Hapus Data?",
      text: "",
      icon: "warning",
      showCancelButton: true,
      cancelButtonColor: "#3085d6",
      confirmButtonColor: "#d33",
      confirmButtonText: "Hapus",
    }).then((result) => {
      if (result.isConfirmed) {
        doDelete(id);
      }
    });
  };

  function successSubmitDelete(redirect: string) {
    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then(() => {
      if (redirect === window.location.pathname) {
        fetch(redirect, { method: "GET", cache: "reload" }).then(() => {
          // console.log("Data diperbarui.");
        });
      } else {
        window.location.href = redirect;
      }
    });
  }

  const onReady = (ws: any) => {
    setWavesurfer(ws);
    setIsPlaying(false);
  };

  const onPlayPause = () => {
    wavesurfer && wavesurfer.playPause();
  };

  return (
    <>
      <DeleteConfirmationDialog
        open={deleteModalOpen}
        onClose={() => setDeleteModalOpen(false)}
        onConfirm={onDeleteEventAction}
        defaultToast={false}
      />
      <Dialog open={open} onOpenChange={onClose}>
        <DialogContent
          onPointerDownOutside={onClose}
          className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[700px] max-h-[80vh] overflow-y-auto"
        >
          <DialogHeader>
            <DialogTitle>
              {event?.length > 1
                ? "Edit Agenda Setting"
                : "Create Agenda Setting"}{" "}
              {event?.title}
            </DialogTitle>
          </DialogHeader>

          <div className="mt-6 h-full ">
            <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>
                  <Controller
                    control={control}
                    name="title"
                    render={({ field }) => (
                      <Input
                        size="md"
                        type="text"
                        value={field.value}
                        onChange={field.onChange}
                        placeholder="Enter Title"
                      />
                    )}
                  />
                  {errors?.title?.message && (
                    <div className="text-destructive text-sm">
                      {typeof errors?.title?.message === "string"
                        ? errors?.title?.message
                        : JSON.stringify(errors?.title?.message)}
                    </div>
                  )}
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="date">Tanggal</Label>
                  <Popover open={isDatePickerOpen} onOpenChange={() => setIsDatePickerOpen(true)}>
                    <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",
                          !date && "text-muted-foreground"
                        )}
                      >
                        <CalendarIcon className="h-4 w-4 mr-2" />
                        {date?.from ? (
                          date.to ? (
                            <>
                              {format(date.from, "LLL dd, y")} -{" "}
                              {format(date.to, "LLL dd, y")}
                            </>
                          ) : (
                            format(date.from, "LLL dd, y")
                          )
                        ) : (
                          <span>Pick a date</span>
                        )}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto p-0" align="start">
                      <Calendar
                        initialFocus
                        mode="range"
                        defaultMonth={date?.from}
                        selected={date}
                        onSelect={(newDate) => {
                          // console.log("Date selected:", newDate);
                          setDate(newDate);
                          if (newDate?.from && newDate?.to) {
                            setIsDatePickerOpen(false);
                          }
                        }}
                        numberOfMonths={1}
                        className="rounded-md border"
                      />
                    </PopoverContent>
                  </Popover>
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="wilayahPublish">Jenis Agenda</Label>
                  <div className="flex flex-wrap items-center gap-2">
                    <div>
                      <Checkbox
                        id="semua"
                        checked={wilayahPublish.semua}
                        onCheckedChange={() => toggleWilayah("semua")}
                      />
                      <label htmlFor="semua" className="ml-2 text-sm">
                        Semua
                      </label>
                    </div>
                    <div>
                      <Checkbox
                        id="nasional"
                        checked={wilayahPublish.nasional}
                        onCheckedChange={() => toggleWilayah("nasional")}
                      />
                      <label htmlFor="nasional" className="ml-2 text-sm mr-2">
                        Nasional
                      </label>
                    </div>
                    <div>
                      <Checkbox
                        id="polda"
                        checked={wilayahPublish.polda}
                        onCheckedChange={() => toggleWilayah("polda")}
                      />
                      <label htmlFor="polda" className="mx-2 text-sm mr-2">
                        Polda
                      </label>
                      {wilayahPublish.polda && (
                        <UnitMapping
                          unit="Polda"
                          isDetail={isDetailMode} 
                          initData={selectedPolda}
                          sendDataToParent={(data: any) =>
                            setSelectedPolda(data)
                          }
                        />
                      )}
                    </div>
                    <div>
                      <Checkbox
                        id="polres"
                        checked={wilayahPublish.polres}
                        onCheckedChange={() => toggleWilayah("polres")}
                      />
                      <label htmlFor="polres" className="ml-2 text-sm mr-2">
                        Polres
                      </label>
                      {wilayahPublish.polres && (
                        <UnitMapping
                          unit="Polres"
                          isDetail={isDetailMode}
                          initData={selectedPolres}
                          sendDataToParent={(data: any) =>
                            setSelectedPolres(data)
                          }
                        />
                      )}
                    </div>
                    <div>
                      <Checkbox
                        id="satker"
                        checked={wilayahPublish.satker}
                        onCheckedChange={() => toggleWilayah("satker")}
                      />
                      <label htmlFor="satker" className="mx-2 text-sm mr-2">
                        Satker
                      </label>
                      {wilayahPublish.satker && (
                        <UnitMapping
                          unit="Satker"
                          isDetail={isDetailMode}
                          initData={selectedSatker}
                          sendDataToParent={(data: any) =>
                            setSelectedSatker(data)
                          }
                        />
                      )}
                    </div>
                    <div>
                      <Checkbox
                        id="international"
                        checked={wilayahPublish.international}
                        onCheckedChange={() => toggleWilayah("international")}
                      />
                      <label
                        htmlFor="international"
                        className="ml-2 text-sm mr-2"
                      >
                        Internasional
                      </label>
                    </div>
                  </div>
                </div>

                <div className="space-y-1.5">
                  <Label htmlFor="description">Isi Agenda Setting</Label>
                  <Controller
                    control={control}
                    name="description"
                    render={({ field }) => (
                      <Textarea
                        value={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>

                <div className="space-y-1.5">
                  <Label htmlFor="attachments">Lampiran</Label>
                  <div className="space-y-3">
                    <div>
                      <Label>Video</Label>
                      <FileUploader
                        accept={{
                          "mp4/*": [],
                          "mov/*": [],
                        }}
                        maxSize={100}
                        label="Upload file dengan format .mp4 atau .mov."
                        onDrop={(files) => setVideoFiles(files)}
                      />
                      {videoUploadedFiles?.map((file: any, index: number) => (
                        <div>
                          <video
                            className="object-fill h-full w-full rounded-md"
                            src={file.url}
                            controls
                            title={`Video ${file.id}`} // Mengganti alt dengan title
                          />
                          <div
                            key={index}
                            className=" flex justify-between border px-3.5 py-3 my-6 rounded-md"
                          >
                            <div className="flex gap-3 items-center">
                              <div className="file-preview">
                                {renderFilePreview(file.url)}
                              </div>
                              <div>
                                <div className=" text-sm  text-card-foreground">
                                  {file.fileName}
                                </div>
                              </div>
                            </div>

                            <Button
                              size="icon"
                              color="destructive"
                              variant="outline"
                              className=" border-none rounded-full"
                              onClick={() => handleRemoveFile(file)}
                            >
                              <Icon icon="tabler:x" className=" h-5 w-5" />
                            </Button>
                          </div>
                        </div>
                      ))}
                    </div>
                    <div>
                      <Label>Foto</Label>
                      <FileUploader
                        accept={{
                          "image/*": [],
                        }}
                        maxSize={100}
                        label="Upload file dengan format .png, .jpg, atau .jpeg."
                        onDrop={(files) => setImageFiles(files)}
                      />
                      {imageUploadedFiles?.map((file: any, index: number) => (
                        <div>
                          <Card className="mt-2">
                            <img
                              src={file.url}
                              alt="Thumbnail Gambar Utama"
                              className="w-full h-auto rounded-md"
                            />
                          </Card>
                          <div
                            key={index}
                            className=" flex justify-between border px-3.5 py-3 my-6 rounded-md"
                          >
                            <div className="flex gap-3 items-center">
                              <div className="file-preview">
                                {renderFilePreview(file.url)}
                              </div>
                              <div>
                                <div className=" text-sm  text-card-foreground">
                                  {file.fileName}
                                </div>
                              </div>
                            </div>

                            <Button
                              size="icon"
                              color="destructive"
                              variant="outline"
                              className=" border-none rounded-full"
                              onClick={() => handleRemoveFile(file)}
                            >
                              <Icon icon="tabler:x" className=" h-5 w-5" />
                            </Button>
                          </div>
                        </div>
                      ))}
                    </div>
                    <div>
                      <Label>Teks</Label>

                      <FileUploader
                        accept={{
                          "pdf/*": [],
                        }}
                        maxSize={100}
                        label="Upload file dengan format .pdf."
                        onDrop={(files) => setTextFiles(files)}
                      />
                      {textUploadedFiles?.map((file: any, index: number) => (
                        <div>
                          <iframe
                            className="w-full h-96 rounded-md"
                            src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
                              file.url
                            )}`}
                            title={file.fileName || "Document"}
                          />
                          <div
                            key={index}
                            className=" flex justify-between border px-3.5 py-3 my-6 rounded-md"
                          >
                            <div className="flex gap-3 items-center">
                              <div className="file-preview">
                                {renderFilePreview(file.url)}
                              </div>
                              <div>
                                <div className=" text-sm  text-card-foreground">
                                  {file.fileName}
                                </div>
                              </div>
                            </div>

                            <Button
                              size="icon"
                              color="destructive"
                              variant="outline"
                              className=" border-none rounded-full"
                              onClick={() => handleRemoveFile(file)}
                            >
                              <Icon icon="tabler:x" className=" h-5 w-5" />
                            </Button>
                          </div>
                        </div>
                      ))}
                    </div>
                    <div>
                      <Label>Audio</Label>
                      <AudioRecorder
                        onRecordingComplete={addAudioElement}
                        audioTrackConstraints={{
                          noiseSuppression: true,
                          echoCancellation: true,
                        }}
                        downloadOnSavePress={true}
                        downloadFileExtension="webm"
                      />
                      <FileUploader
                        accept={{
                          "mp3/*": [],
                          "wav/*": [],
                        }}
                        maxSize={100}
                        label="Upload file dengan format .mp3 atau .wav."
                        onDrop={(files) =>
                          setAudioFiles((prev) => [...prev, ...files])
                        }
                        className="mt-2"
                      />
                      {audioUploadedFiles?.map((file: any, index: number) => (
                        <div>
                          <div key={file.id}>
                            <WavesurferPlayer
                              height={500}
                              waveColor="red"
                              url={file.url}
                              onReady={onReady}
                              onPlay={() => setIsPlaying(true)}
                              onPause={() => setIsPlaying(false)}
                            />
                          </div>
                          <Button
                            size="sm"
                            type="button"
                            onClick={onPlayPause}
                            disabled={isPlaying}
                            className={`flex items-center gap-2 ${
                              isPlaying
                                ? "bg-gray-300 cursor-not-allowed"
                                : "bg-primary text-white"
                            } p-2 rounded`}
                          >
                            {isPlaying ? "Pause" : "Play"}
                            <Icon
                              icon={
                                isPlaying
                                  ? "carbon:pause-outline"
                                  : "famicons:play-sharp"
                              }
                              className="h-5 w-5"
                            />
                          </Button>

                          <div
                            key={index}
                            className=" flex justify-between border px-3.5 py-3 my-6 rounded-md"
                          >
                            <div className="flex gap-3 items-center">
                              <div className="file-preview">
                                <Music />
                              </div>
                              <div>
                                <div className=" text-sm  text-card-foreground">
                                  {file.fileName}
                                </div>
                              </div>
                            </div>

                            <Button
                              size="icon"
                              color="destructive"
                              variant="outline"
                              className=" border-none rounded-full"
                              onClick={() => handleRemoveFile(file)}
                            >
                              <Icon icon="tabler:x" className=" h-5 w-5" />
                            </Button>
                          </div>
                        </div>
                      ))}
                    </div>
                    {audioFile && (
                      <div className="flex flex-row justify-between items-center">
                        <div className="flex items-center mr-1">
                          {" "}
                          <Music /> <p>Voice Note</p>
                        </div>
                        <Button
                          type="button"
                          onClick={handleDeleteAudio}
                          size="sm"
                          color="destructive"
                        >
                          X
                        </Button>
                      </div>
                    )}
                    {isRecording && (
                      <p>Recording... {timer} seconds remaining</p>
                    )}{" "}
                    {/* Display remaining time */}
                  </div>
                </div>
              </div>
              {detailData && (
                <div>
                  {roleId == 11 || roleId == 12 ? (
                    <Button
                      variant={"outline"}
                      color="primary"
                      onClick={() => save(detailData, true)}
                      disabled={isPublishing}
                    >
                      {isPublishing ? "Publishing..." : "Kirim Ke Mabes"}
                    </Button>
                  ) : (
                    ""
                  )}
                </div>
              )}

              <div className="flex flex-wrap  gap-2 mt-10">
                <Button
                  style={
                    roleId > 12
                      ? {
                          display: "none",
                        }
                      : {}
                  }
                  type="submit"
                  disabled={isPending}
                  className="flex-1"
                >
                  {isPending ? (
                    <>
                      <Loader2 className="me-2 h-4 w-4 animate-spin" />
                      {event?.length > 1 ? "Updating..." : "Adding..."}
                    </>
                  ) : event?.length > 1 ? (
                    "Update Agenda Setting"
                  ) : (
                    "Simpan Agenda Setting"
                  )}
                </Button>
                <Button
                  style={
                    roleId > 12 
                      ? {
                          display: "none",
                        }
                      : {}
                  }
                  className="flex-1 bg-red-500 text-white"
                  type="button"
                  onClick={() => handleDelete(event?.event?.id)}
                >
                  Delete
                </Button>
                {event?.length > 1 && (
                  <Button
                    type="button"
                    color="destructive"
                    onClick={() => handleOpenDeleteModal(event?.event?.id)}
                    className="flex-1"
                  >
                    Delete
                  </Button>
                )}
              </div>
            </form>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
};

export default EventModal;
