// "use client";
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";
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 } 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";

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

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 [calendarProps, setCalendarProps] = 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 {
    register,
    control,
    reset,
    setValue,
    formState: { errors },
    handleSubmit,
  } = useForm({
    resolver: zodResolver(schema),
    mode: "all",
  });

  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) => {
    if (!audioFile) return;

    const formData = new FormData();
    formData.append("voiceNote", audioFile);

    const reqData = {
      title: data.title,
      description: data.description || "",
      agendaType: calendarProps,
      startDate: format(startDate, "yyyy-MM-dd"),
      endDate: format(endDate, "yyyy-MM-dd"),
      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(() => {
      router.push("/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;
      setCalendarProps(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) => {
    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());
  };

  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 ? "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>
                  <Input
                    id="title"
                    type="text"
                    placeholder="Enter Event Name"
                    {...register("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="calendarProps">Jenis Agenda </Label>
                  <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>
                {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>
                  <Textarea
                    id="description"
                    placeholder="Enter Event Name"
                    {...register("description")}
                  />
                  {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>
                      <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>
              </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"
                  ) : (
                    "Simpan Agenda Setting"
                  )}
                </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;
