// "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 } from "@/lib/utils";
import { format } 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 } from "lucide-react";
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 { useRouter } from "next/navigation";
import { postSchedule } from "@/service/schedule/schedule";
import { 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 FileUploaderMultiple from "@/components/form/shared/file-uploaded";
import { Upload } from "tus-js-client";

const schema = z.object({
  title: z.string().min(3, { message: "Required" }),
  description: z.string().min(3, { message: "Required" }),
});

interface FileWithPreview extends File {
  preview: string;
}

const EventModal = ({
  open,
  onClose,
  categories,
  event,
  selectedDate,
}: {
  open: boolean;
  onClose: () => void;
  categories: any;
  event: any;
  selectedDate: any;
}) => {
  const [startDate, setStartDate] = useState<Date>(new Date());
  const [endDate, setEndDate] = useState<Date>(new Date());
  const [isPending, startTransition] = React.useTransition();
  const [agendaType, setAgendaType] = React.useState<any>(
    categories[0].value
  );
  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 [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 [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 {
    register,
    control,
    reset,
    setValue,
    formState: { errors },
    handleSubmit,
  } = useForm({
    resolver: zodResolver(schema),
    mode: "all",
  });

  useEffect(() => {
    async function fetchPoldaPolres() {
      setIsLoading(true);
      try {
        const response = await getUserLevelForAssignments();
        const levelList = response?.data?.data.list;
        let listFiltered = [];
        if (agendaType == "polda") {
          listFiltered = levelList.filter((level: any) => level.name != 'SATKER POLRI');
        } else if (agendaType == "polres") {
          listFiltered = levelList.filter((level: any) => level.name != 'SATKER POLRI');
        } else if (agendaType == "satker") {
          listFiltered = levelList.filter((level: any) => level.name == 'SATKER POLRI');
        }
        setListDest(listFiltered);
        const initialExpandedState = listFiltered.reduce(
          (acc: any, polda: any) => {
            acc[polda.id] = false;
            return acc;
          },
          {}
        );
        setExpandedPolda(initialExpandedState);
      } catch (error) {
        console.error("Error fetching Polda/Polres data:", error);
      } finally {
        setIsLoading(false);
      }
    }
    fetchPoldaPolres();
    console.log("Event", event);
  }, [agendaType]);

  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) => {
    // const formData = new FormData();
    // formData.append("voiceNote", audioFile);

    const reqData = {
      title: data.title,
      description: data.description,
      agendaType: agendaType,
      startDate: format(startDate, "yyyy-MM-dd"),
      endDate: format(endDate, "yyyy-MM-dd"),
    };

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

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

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

    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: any, index: number) => {
      await uploadResumableFile(
        index,
        String(id),
        item,
        "4",
        "0"
      );
    });

    // Optional: Use Swal for success feedback
    // MySwal.fire({
    //   title: "Sukses",
    //   text: "Data berhasil disimpan.",
    //   icon: "success",
    //   confirmButtonColor: "#3085d6",
    //   confirmButtonText: "OK",
    // }).then(() => {
    //   router.push("en/contributor/agenda-setting");
    // });
  };

  const onSubmit = (data: any) => {
    save(data);
  };

  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;
      setAgendaType(eventCalendar || 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);

    // 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());
  };

  async function uploadResumableFile(
      idx: number,
      id: string,
      file: any,
      fileTypeId: string,
      duration: string
  ) {
    console.log(idx, id, file, fileTypeId, duration);

    // const placements = getPlacement(file.placements);
    // console.log("Placementttt:  : ", placements);

    const upload = new Upload(file, {
      endpoint: `${process.env.NEXT_PUBLIC_API}/agenda-settings/file/upload`,
      retryDelays: [0, 3000, 6000, 12_000, 24_000],
      chunkSize: 20_000,
      metadata: {
        agendaSettingId: id,
        filename: file.name,
        filetype: file.type,
        fileTypeId: fileTypeId,
        duration: "",
        isWatermark: "true", // hardcode
      },
      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);
    });
  };

  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="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="agendaType">Jenis Agenda </Label>
                  <Controller
                    name="agendaType"
                    control={control}
                    render={({ field }) => (
                      <Select
                        value={agendaType}
                        onValueChange={(data) => setAgendaType(data)}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Label" />
                        </SelectTrigger>
                        <SelectContent>
                          {categories.map((category: CalendarCategory) => (
                            <SelectItem
                              value={category.value}
                              key={category.value}
                            >
                              {category.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    )}
                  />
                </div>
                {(agendaType === "polda" || agendaType === "polres" || agendaType === "satker" )&& (
                  <div>
                    <Dialog>
                      <DialogTrigger asChild>
                        <Button variant="soft" size="sm" color="primary">
                          [Pilih {agendaType}]
                        </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>
                              {(agendaType == "polres" || agendaType == "satker") && 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>
                  <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>
                <div className="space-y-1.5">
                  <Label htmlFor="attachments">Lampiran</Label>
                  <div className="space-y-3">
                    <div>
                      <Label>Video</Label>
                      <FileUploaderMultiple 
                        accept={{
                          "mp4/*": [],
                          "mov/*": [],
                        }}
                        maxSize={100}
                        label="Upload file dengan format .mp4 atau .mov."
                        onDrop={(files) => setImageFiles(files)}
                      />
                    </div>
                    <div>
                      <Label>Foto</Label>
                      <FileUploaderMultiple 
                        accept={{
                          "image/*": [],
                        }}
                        maxSize={100}
                        label="Upload file dengan format .png, .jpg, atau .jpeg."
                        onDrop={(files) => setImageFiles(files)}
                      />
                    </div>
                    <div>
                      <Label>Teks</Label>
                      <FileUploaderMultiple 
                        accept={{
                          "pdf/*": [],
                        }}
                        maxSize={100}
                        label="Upload file dengan format .pdf."
                        onDrop={(files) => setTextFiles(files)}
                      />
                    </div>
                    <div>
                      <Label>Voice Note</Label>
                      <AudioRecorder
                        onRecordingComplete={addAudioElement}
                        audioTrackConstraints={{
                          noiseSuppression: true,
                          echoCancellation: true,
                        }}
                        downloadOnSavePress={true}
                        downloadFileExtension="webm"
                      />
                      <FileUploaderMultiple 
                        accept={{
                          "mp3/*": [],
                          "wav/*": [],
                        }}
                        maxSize={100}
                        label="Upload file dengan format .mp3 atau .wav."
                        onDrop={(files) => setAudioFiles(files)}
                        className="mt-2"
                      />
                    </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>
              </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?.length > 1  ? "Updating..." : "Adding..."}
                    </>
                  ) : event?.length > 1  ? (
                    "Update Agenda Setting"
                  ) : (
                    "Simpan Agenda Setting"
                  )}
                </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;
