"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter } from "next/navigation";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";

import {
  createTask,
  getTask,
  getUserLevelForAssignments,
} from "@/service/task";
import { getContestById, postCreateContest } from "@/service/contest/contest";
import page from "@/app/[locale]/page";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { cn, getCookiesDecrypt } from "@/lib/utils";
import { CalendarIcon, ChevronDown, ChevronUp, Trash2 } from "lucide-react";
import { format, parseISO } from "date-fns";
import { Calendar } from "@/components/ui/calendar";
import { DateRange } from "react-day-picker";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import dynamic from "next/dynamic";
import Cookies from "js-cookie";
import FileUploader from "../shared/file-uploader";
import { AudioRecorder } from "react-audio-voice-recorder";
import { error, loading } from "@/lib/swal";
import { Upload } from "tus-js-client";
import { getCsrfToken } from "@/service/auth";
import { getOnlyDate } from "@/utils/globals";
import { duration } from "moment";

const contestSchema = z.object({
  theme: z.string().min(1, { message: "Judul diperlukan" }),
  duration: z
    .array(z.string().min(1)) // Gunakan array string untuk menyimpan range tanggal
    .min(1, { message: "Tanggal diperlukan" }),
  hastagCode: z.string().min(1, { message: "Judul diperlukan" }),
  description: z.string().min(2, {
    message: "Narasi Penugasan harus lebih dari 2 karakter.",
  }),
  scoringFormula: z.string().min(2, {
    message: "Narasi Penugasan harus lebih dari 2 karakter.",
  }),
});

export type contestDetail = {
  id: number;
  theme: string;
  hastagCode: string;
  assignedToTopLevel: string;
  assignmentType: {
    id: number;
    name: string;
  };
  assignmentMainType: {
    id: number;
    name: string;
  };
  duration: string;
  platformType: string | null;
  assignmentTypeId: string;
  targetOutput: string;
  targetParticipantTopLevel: string;
  description: string;
  fileTypeOutput: any;
  is_active: string;
};

const CustomEditor = dynamic(
  () => {
    return import("@/components/editor/custom-editor");
  },
  { ssr: false }
);

interface FileWithPreview extends File {
  preview: string;
}

export default function FormContestDetail() {
  const MySwal = withReactContent(Swal);
  const userRoleId = Number(getCookiesDecrypt("urie"));
  const userLevelId = Number(getCookiesDecrypt("ulie"));
  const userLevelNumber = Number(getCookiesDecrypt("ulne"));
  const router = useRouter();
  const editor = useRef(null);
  type ContestSchema = z.infer<typeof contestSchema>;
  const { id } = useParams() as { id: string };
  console.log(id);
  const [mainType, setMainType] = useState<string>("1");
  const [broadcastType, setBroadcastType] = useState<string>(""); // untuk Tipe Penugasan
  const [selectedTarget, setSelectedTarget] = useState("all");
  const [detail, setDetail] = useState<any>();
  const [refresh] = useState(false);
  const [date, setDate] = useState<DateRange | undefined>();
  const [listDest, setListDest] = useState<any[]>([]);
  const [checkedLevels, setCheckedLevels] = useState<Set<number>>(new Set());
  const [expandedPolda, setExpandedPolda] = useState<Record<number, boolean>>({});
  const [isLoading, setIsLoading] = useState(false);
  const [audioFile, setAudioFile] = useState<File | null>(null);
  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 [isRecording, setIsRecording] = useState(false);
  const [timer, setTimer] = useState<number>(120);
  const [links, setLinks] = useState<string[]>([""]);

  const [platformTypeVisible, setPlatformTypeVisible] = useState(false);

  const [taskOutput, setTaskOutput] = useState({
    all: false,
    video: false,
    audio: false,
    image: false,
    text: false,
  });

  const [unitSelection, setUnitSelection] = useState({
    allUnit: false,
    mabes: false,
    polda: false,
    polres: false,
    satker: false,
  });

  // State untuk melacak apakah perubahan berasal dari checkbox Pelaksana Tugas
  const [isUpdatingFromPelaksana, setIsUpdatingFromPelaksana] = useState(false);
  // State untuk melacak jenis perubahan spesifik
  const [pelaksanaChangeType, setPelaksanaChangeType] = useState<string>("");

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<ContestSchema>({
    resolver: zodResolver(contestSchema),
  });

  // const handleRadioChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  //   const selectedValue = Number(event.target.value);
  //   setMainType(selectedValue);

  //   setPlatformTypeVisible(selectedValue === 2);
  // };

  useEffect(() => {
    async function fetchPoldaPolres() {
      setIsLoading(true);
      try {
        const response = await getUserLevelForAssignments();
        setListDest(response?.data?.data.list);
        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();
  }, []);

  // useEffect untuk sinkronisasi checkbox modal dengan Pelaksana Tugas
  // Ketika unitSelection berubah dari checkbox Pelaksana Tugas:
  // - Jika di-checklist: checklist semua item sesuai kategori di modal
  // - Jika di-unchecklist: unchecklist semua item di modal
  useEffect(() => {
    if (listDest.length > 0) {
      syncModalWithUnitSelection();
    }
  }, [unitSelection, listDest]);

  useEffect(() => {
    async function initState() {
      if (id) {
        const response = await getContestById(id);
        const details = response?.data?.data;

        setDetail(details);
        if (details?.duration) {
          const [start, end] = details.duration.split(" - "); // Pisahkan tanggal
          setDate({
            from: parseISO(start),
            to: end ? parseISO(end) : undefined, // Pastikan `to` bisa undefined jika hanya satu tanggal
          });
        }
      }
    }
    initState();
  }, [id, refresh]);

  useEffect(() => {
    if (detail?.targetOutput) {
      const outputSet = new Set(detail.targetOutput.split(",").map(Number)); // Membagi string ke dalam array dan mengonversi ke nomor
      setTaskOutput({
        all: outputSet.has(0),
        video: outputSet.has(2),
        audio: outputSet.has(4),
        image: outputSet.has(1),
        text: outputSet.has(3),
      });
    }
  }, [detail?.targetOutput]);

  useEffect(() => {
    if (detail?.targetOutput) {
      const outputSet = new Set(detail.targetOutput.split(",").map(Number));
      setUnitSelection({
        allUnit: outputSet.has(0),
        mabes: outputSet.has(1),
        polda: outputSet.has(2),
        polres: outputSet.has(3),
        satker: outputSet.has(4),
      });
    }
  }, [detail?.targetOutput]);

  // Fungsi untuk update unitSelection berdasarkan checkbox modal
  // Checkbox di Pelaksana Tugas hanya akan aktif jika SEMUA item dalam kategori tersebut dichecklist
  const updateUnitSelectionFromModal = (levelId: number) => {
    setTimeout(() => {
      // Hitung total item yang tersedia untuk setiap kategori
      const totalPolda = listDest.filter((item: any) => 
        item.levelNumber === 2 && item.name !== "SATKER POLRI"
      ).length;
      
      const totalPolres = listDest.reduce((total: number, item: any) => {
        if (item.subDestination) {
          return total + item.subDestination.length;
        }
        return total;
      }, 0);
      
      const satkerItem = listDest.find((item: any) => item.name === "SATKER POLRI");
      const totalSatker = satkerItem ? (1 + (satkerItem.subDestination?.length || 0)) : 0;
      
      // Hitung item yang dichecklist untuk setiap kategori
      const checkedPoldaCount = listDest.filter((item: any) => 
        item.levelNumber === 2 && 
        item.name !== "SATKER POLRI" && 
        checkedLevels.has(item.id)
      ).length;
      
      const checkedPolresCount = listDest.reduce((total: number, item: any) => {
        if (item.subDestination) {
          return total + item.subDestination.filter((sub: any) => checkedLevels.has(sub.id)).length;
        }
        return total;
      }, 0);
      
      const checkedSatkerCount = satkerItem ? (
        (checkedLevels.has(satkerItem.id) ? 1 : 0) + 
        (satkerItem.subDestination?.filter((sub: any) => checkedLevels.has(sub.id)).length || 0)
      ) : 0;
      
      // Checkbox hanya aktif jika SEMUA item dalam kategori tersebut dichecklist
      const hasCheckedPolda = totalPolda > 0 && checkedPoldaCount === totalPolda;
      const hasCheckedPolres = totalPolres > 0 && checkedPolresCount === totalPolres;
      const hasCheckedSatker = totalSatker > 0 && checkedSatkerCount === totalSatker;
      
      // Update unitSelection berdasarkan checkbox yang aktif di modal
      setUnitSelection(prev => ({
        ...prev,
        polda: hasCheckedPolda,
        polres: hasCheckedPolres,
        satker: hasCheckedSatker,
        // allUnit hanya true jika semua kategori terpenuhi
        allUnit: hasCheckedPolda && hasCheckedPolres && hasCheckedSatker
      }));
    }, 0);
  };

  const handleCheckboxChange = (levelId: number) => {
    setCheckedLevels((prev) => {
      const updatedLevels = new Set(prev);
      if (updatedLevels.has(levelId)) {
        updatedLevels.delete(levelId);
      } else {
        updatedLevels.add(levelId);
      }
      return updatedLevels;
    });
    
    // Update unitSelection berdasarkan perubahan di modal
    updateUnitSelectionFromModal(levelId);
  };

  // Fungsi untuk sinkronisasi checkbox modal dengan Pelaksana Tugas
  const syncModalWithUnitSelection = () => {
    // Hanya jalankan sinkronisasi jika perubahan berasal dari checkbox Pelaksana Tugas
    if (isUpdatingFromPelaksana) {
      // Khusus untuk unchecklist POLRES: hanya unchecklist polres, pertahankan polda
      if (pelaksanaChangeType === "polres_unchecked") {
        const newCheckedLevels = new Set<number>(checkedLevels);
        
        // Hapus semua polres dari modal, tapi pertahankan polda
        listDest.forEach((item: any) => {
          if (item.subDestination && item.levelNumber === 2 && item.name !== "SATKER POLRI") {
            item.subDestination.forEach((polres: any) => {
              newCheckedLevels.delete(polres.id);
            });
          }
        });
        
        setCheckedLevels(newCheckedLevels);
      }
      // Untuk perubahan lainnya, jalankan logika normal
      else if (unitSelection.polda || unitSelection.polres || unitSelection.satker) {
        // Mulai dengan checkbox yang sudah ada untuk mempertahankan pilihan manual user
        const newCheckedLevels = new Set<number>(checkedLevels);
        
        listDest.forEach((item: any) => {
          // Jika polda dichecklist, checklist semua polda (levelNumber 2, bukan SATKER POLRI)
          if (unitSelection.polda && item.levelNumber === 2 && item.name !== "SATKER POLRI") {
            newCheckedLevels.add(item.id);
          }
          
          // Jika satker dichecklist, checklist SATKER POLRI dan sub-itemnya
          if (unitSelection.satker && item.name === "SATKER POLRI") {
            newCheckedLevels.add(item.id);
            if (item.subDestination) {
              item.subDestination.forEach((sub: any) => {
                newCheckedLevels.add(sub.id);
              });
            }
          }
          
          // Jika polres dichecklist
          if (unitSelection.polres && item.subDestination) {
            // Jika checkbox POLDA di Pelaksana Tugas juga aktif, checklist semua polres
            if (unitSelection.polda && item.levelNumber === 2 && item.name !== "SATKER POLRI") {
              item.subDestination.forEach((polres: any) => {
                newCheckedLevels.add(polres.id);
              });
            }
            // Jika checkbox POLDA di Pelaksana Tugas tidak aktif, tapi ada POLDA yang dichecklist di modal
            else if (!unitSelection.polda && item.levelNumber === 2 && item.name !== "SATKER POLRI") {
              // Cek apakah POLDA ini sudah dichecklist di modal
              if (checkedLevels.has(item.id)) {
                // Jika ya, checklist semua polres dari POLDA ini
                item.subDestination.forEach((polres: any) => {
                  newCheckedLevels.add(polres.id);
                });
              }
            }
          }
        });
        
        setCheckedLevels(newCheckedLevels);
      } else {
        // Jika tidak ada unitSelection yang aktif, unchecklist semua item di modal
        // Setelah itu user bisa checklist secara manual
        setCheckedLevels(new Set<number>());
      }
      
      // Reset flag setelah sinkronisasi selesai
      setTimeout(() => {
        setIsUpdatingFromPelaksana(false);
        setPelaksanaChangeType("");
      }, 100);
    }
  };

  const handlePoldaPolresChange = () => {
    return Array.from(checkedLevels).join(","); // Mengonversi Set ke string
  };

  const save = async (data: ContestSchema) => {
    const fileTypeMapping = {
      all: "0",
      video: "2",
      audio: "4",
      image: "1",
      text: "3",
    };

    const unitMapping = {
      allUnit: "0",
      mabes: "1",
      polda: "2",
      polres: "3",
      satker: "4",
    };

    const assignmentPurposeString = Object.keys(unitSelection)
      .filter((key) => unitSelection[key as keyof typeof unitSelection])
      .map((key) => unitMapping[key as keyof typeof unitMapping])
      .join(",");

    const selectedOutputs = Object.keys(taskOutput)
      .filter((key) => taskOutput[key as keyof typeof taskOutput]) // Ambil hanya yang `true`
      .map((key) => fileTypeMapping[key as keyof typeof fileTypeMapping]) // Konversi ke nilai string
      .join(",");

    // Pastikan `data.duration` ada dan dikonversi ke `Date`
    const startDate = data.duration?.[0] ? new Date(data.duration[0]) : null;
    const endDate = data.duration?.[1] ? new Date(data.duration[1]) : null;

    const formattedDuration = startDate
      ? endDate
        ? `${getOnlyDate(startDate)} - ${getOnlyDate(endDate)}`
        : getOnlyDate(startDate)
      : "";

    const requestData: {
      id?: any;
      theme: string;
      duration: string;
      targetParticipantTopLevel: any;
      targetParticipant: any;
      hastagCode: string;
      description: string;
      scoringFormula: string;
      targetOutput: any;
      attachmentUrl: string[];
    } = {
      ...data,
      hastagCode: data.hastagCode,
      theme: data.theme,
      duration: formattedDuration,
      description: data.description,
      scoringFormula: data.scoringFormula,
      targetParticipantTopLevel: handlePoldaPolresChange(),
      targetParticipant: assignmentPurposeString,
      targetOutput: selectedOutputs,
      attachmentUrl: links,
    };

    // if (id != undefined) {
    //   requestData.id = id;
    // }

    const response = await postCreateContest(requestData);

    console.log("Form Data Submitted:", requestData);
    console.log("response", response);

    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, // Use .file to access the actual File object
        "4",
        "0" // Optional: Replace with actual duration if available
      );
    });
  };

  const onSubmit = (data: ContestSchema) => {
    MySwal.fire({
      title: "Simpan Data",
      text: "Apakah Anda yakin ingin menyimpan data ini?",
      icon: "warning",
      showCancelButton: true,
      cancelButtonColor: "#d33",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Simpan",
    }).then((result) => {
      if (result.isConfirmed) {
        save(data);
      }
    });
  };

  const toggleExpand = (poldaId: any) => {
    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); // 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 and add preview
    const fileWithPreview: FileWithPreview = Object.assign(
      new File([blob], "voiceNote.webm", { type: "audio/webm" }),
      { preview: url }
    );

    // Add to state
    setAudioFile(fileWithPreview);
    setAudioFiles((prev) => [...prev, fileWithPreview]);
  };

  const handleDeleteAudio = (index: number) => {
    setAudioFiles((prev) => prev.filter((_, idx) => idx !== index));
  };

  async function uploadResumableFile(
    idx: number,
    id: string,
    file: any,
    fileTypeId: string,
    duration: string
  ) {
    console.log("Param Upload : ", 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}/contest/file/upload`,
      headers: headers,
      retryDelays: [0, 3000, 6000, 12_000, 24_000],
      chunkSize: 20_000,
      metadata: {
        contestId: 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/shared/contest");
    }
  }

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

  const handleLinkChange = (index: number, value: string) => {
    const updatedLinks = [...links];
    updatedLinks[index] = value;
    setLinks(updatedLinks);
  };

  const handleAddRow = () => {
    setLinks([...links, ""]);
  };

  // Remove a specific link row
  const handleRemoveRow = (index: number) => {
    const updatedLinks = links.filter((_: any, i: any) => i !== index);
    setLinks(updatedLinks);
  };

  return (
    <Card>
      <div className="px-6 py-6">
        <p className="text-lg font-semibold mb-3">Form Contest</p>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="gap-5 mb-5">
            <div className="space-y-2">
              <Label>Kode Lomba</Label>
              <Controller
                control={control}
                name="hastagCode"
                render={({ field: { onChange, value } }) => (
                  <Input
                    size="md"
                    type="text"
                    value={detail?.hastagCode || value}
                    onChange={onChange}
                    placeholder="Enter hastagCode"
                  />
                )}
              />
              {errors.hastagCode?.message && (
                <p className="text-red-400 text-sm">
                  {errors.hastagCode.message}
                </p>
              )}
            </div>
            {/* Input Title */}
            <div className="space-y-2 mt-5">
              <Label>Judul Lomba</Label>
              <Controller
                control={control}
                name="theme"
                render={({ field: { onChange, value } }) => (
                  <Input
                    size="md"
                    type="text"
                    value={detail?.theme || value}
                    onChange={onChange}
                    placeholder="Enter theme"
                  />
                )}
              />
              {errors.theme?.message && (
                <p className="text-red-400 text-sm">{errors.theme.message}</p>
              )}
            </div>
            <div className="flex flex-col mt-5">
              <Label className="mr-3 mb-1">Tanggal</Label>
              <Controller
                control={control}
                name="duration"
                render={({ field: { onChange, value } }) => (
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button
                        id="date"
                        variant={"outline"}
                        className={cn(
                          "w-[280px] lg:w-[300px] justify-start text-left font-normal",
                          !date && "text-muted-foreground"
                        )}
                        value={detail?.duration}
                      >
                        <CalendarIcon />
                        {date?.from ? (
                          date.to ? (
                            <>
                              {format(date.from, "yyyy-MM-dd")} -{" "}
                              {format(date.to, "yyyy-MM-dd")}
                            </>
                          ) : (
                            format(date.from, "yyyy-MM-dd")
                          )
                        ) : (
                          <span>Pilih Tanggal</span>
                        )}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto p-0" align="start">
                      <Calendar
                        initialFocus
                        mode="range"
                        defaultMonth={date?.from}
                        selected={date}
                        onSelect={(newDate) => {
                          setDate(newDate); // Update state lokal
                          if (newDate?.from) {
                            const formattedDate = [
                              format(newDate.from, "yyyy-MM-dd"),
                              newDate.to
                                ? format(newDate.to, "yyyy-MM-dd")
                                : "",
                            ].filter(Boolean); // Hanya menyimpan yang tidak undefined
                            onChange(formattedDate); // Simpan ke React Hook Form
                          } else {
                            onChange([]); // Reset jika tidak ada tanggal
                          }
                        }}
                        numberOfMonths={1}
                      />
                    </PopoverContent>
                  </Popover>
                )}
              />
              {errors.duration?.message && (
                <p className="text-red-400 text-sm">
                  {errors.duration.message}
                </p>
              )}
            </div>
            <div className="mt-5">
              <Label>Output Lomba</Label>
              <div className="flex flex-wrap gap-3 mt-2">
                {Object.keys(taskOutput).map((key) => (
                  <div className="flex items-center gap-2" key={key}>
                    <Checkbox
                      id={key}
                      checked={taskOutput[key as keyof typeof taskOutput]}
                      onCheckedChange={(value) => {
                        if (key === "all") {
                          const newValue = Boolean(value);
                          setTaskOutput({
                            all: newValue,
                            video: newValue,
                            audio: newValue,
                            image: newValue,
                            text: newValue,
                          });
                        } else {
                          setTaskOutput((prev) => {
                            const updated = { ...prev, [key]: Boolean(value) };
                            // Update 'all' jika semua sub-checkbox true
                            const allChecked = Object.entries(updated)
                              .filter(([k]) => k !== "all")
                              .every(([_, v]) => v);
                            return { ...updated, all: allChecked };
                          });
                        }
                      }}
                    />
                    <Label htmlFor={key}>
                      {key.charAt(0).toUpperCase() + key.slice(1)}
                    </Label>
                  </div>
                ))}
              </div>
            </div>
            <div className="flex flex-col mt-7">
              <Label>Pelaksana Tugas</Label>
              <div className="flex flex-row mt-2 gap-3">
                {Object.keys(unitSelection).map((key) => (
                  <div className="flex items-center gap-2" key={key}>
                    <Checkbox
                      id={key}
                      checked={unitSelection[key as keyof typeof unitSelection]}
                      onCheckedChange={(value) => {
                        // Set flag bahwa perubahan berasal dari checkbox Pelaksana Tugas
                        setIsUpdatingFromPelaksana(true);
                        setPelaksanaChangeType(key + (value ? "_checked" : "_unchecked"));
                        
                        if (key === "allUnit") {
                          const newValue = Boolean(value);
                          setUnitSelection({
                            allUnit: newValue,
                            mabes: newValue,
                            polda: newValue,
                            polres: newValue,
                            satker: newValue,
                          });
                        } else {
                          // Validasi khusus untuk POLRES
                          if (key === "polres" && value) {
                            // Cek apakah ada POLDA yang sudah dichecklist di modal
                            const hasCheckedPolda = listDest.some((item: any) => 
                              item.levelNumber === 2 && 
                              item.name !== "SATKER POLRI" && 
                              checkedLevels.has(item.id)
                            );
                            
                            if (!hasCheckedPolda) {
                              // Jika tidak ada POLDA yang dichecklist di modal, tampilkan peringatan dan batalkan
                              alert("Harap pilih POLDA di Modal List terlebih dahulu sebelum mengaktifkan checkbox POLRES.");
                              return; // Batalkan perubahan
                            }
                          }
                          
                          setUnitSelection((prev) => {
                            const updated = { ...prev, [key]: Boolean(value) };
                            // Update 'allUnit' jika semua sub-checkbox true
                            const allChecked = Object.entries(updated)
                              .filter(([k]) => k !== "allUnit")
                              .every(([_, v]) => v);
                            return { ...updated, allUnit: allChecked };
                          });
                        }
                      }}
                    />
                    <Label htmlFor={key}>
                      {key.charAt(0).toUpperCase() + key.slice(1)}
                    </Label>
                  </div>
                ))}
                <div className="  pl-1">
                  <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
                                type="button"
                                onClick={(e) => {
                                  e.preventDefault();
                                  e.stopPropagation();
                                  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);
                                      
                                                                             // Update unitSelection berdasarkan perubahan
                                       setTimeout(() => {
                                         // Hitung total item yang tersedia untuk setiap kategori
                                         const totalPolda = listDest.filter((item: any) => 
                                           item.levelNumber === 2 && item.name !== "SATKER POLRI"
                                         ).length;
                                         
                                         const totalPolres = listDest.reduce((total: number, item: any) => {
                                           if (item.subDestination) {
                                             return total + item.subDestination.length;
                                           }
                                           return total;
                                         }, 0);
                                         
                                         const satkerItem = listDest.find((item: any) => item.name === "SATKER POLRI");
                                         const totalSatker = satkerItem ? (1 + (satkerItem.subDestination?.length || 0)) : 0;
                                         
                                         // Hitung item yang dichecklist untuk setiap kategori
                                         const checkedPoldaCount = listDest.filter((item: any) => 
                                           item.levelNumber === 2 && 
                                           item.name !== "SATKER POLRI" && 
                                           updatedLevels.has(item.id)
                                         ).length;
                                         
                                         const checkedPolresCount = listDest.reduce((total: number, item: any) => {
                                           if (item.subDestination) {
                                             return total + item.subDestination.filter((sub: any) => updatedLevels.has(sub.id)).length;
                                           }
                                           return total;
                                         }, 0);
                                         
                                         const checkedSatkerCount = satkerItem ? (
                                           (updatedLevels.has(satkerItem.id) ? 1 : 0) + 
                                           (satkerItem.subDestination?.filter((sub: any) => updatedLevels.has(sub.id)).length || 0)
                                         ) : 0;
                                         
                                         // Checkbox hanya aktif jika SEMUA item dalam kategori tersebut dichecklist
                                         const hasCheckedPolda = totalPolda > 0 && checkedPoldaCount === totalPolda;
                                         const hasCheckedPolres = totalPolres > 0 && checkedPolresCount === totalPolres;
                                         const hasCheckedSatker = totalSatker > 0 && checkedSatkerCount === totalSatker;
                                         
                                         setUnitSelection(prev => ({
                                           ...prev,
                                           polda: hasCheckedPolda,
                                           polres: hasCheckedPolres,
                                           satker: hasCheckedSatker,
                                           allUnit: hasCheckedPolda && hasCheckedPolres && hasCheckedSatker
                                         }));
                                       }, 0);
                                    }}
                                    className="mr-2"
                                  />
                                  Pilih Semua
                                </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>
            </div>

            <div className="mt-7">
              <Label>Narasi Penugasan</Label>
              <Controller
                control={control}
                name="description"
                render={({ field: { onChange, value } }) => (
                  <CustomEditor
                    onChange={onChange}
                    initialData={detail?.description || value}
                  />
                )}
              />
              {errors.description?.message && (
                <p className="text-red-400 text-sm">
                  {errors.description.message}
                </p>
              )}
            </div>
            <div className="mt-7">
              <Label>Panduan Penilaian</Label>
              <Controller
                control={control}
                name="scoringFormula"
                render={({ field: { onChange, value } }) => (
                  <CustomEditor
                    onChange={onChange}
                    initialData={detail?.scoringFormula || value}
                  />
                )}
              />
              {errors.scoringFormula?.message && (
                <p className="text-red-400 text-sm">
                  {errors.scoringFormula.message}
                </p>
              )}
            </div>
            <div className="space-y-1.5 mt-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)}
                  />
                </div>
                <div>
                  <Label>Foto</Label>
                  <FileUploader
                    accept={{
                      "image/*": [],
                    }}
                    maxSize={100}
                    label="Upload file dengan format .png, .jpg, atau .jpeg."
                    onDrop={(files) => setImageFiles(files)}
                  />
                </div>
                <div>
                  <Label>Teks</Label>
                  <FileUploader
                    accept={{
                      "pdf/*": [],
                    }}
                    maxSize={100}
                    label="Upload file dengan format .pdf."
                    onDrop={(files) => setTextFiles(files)}
                  />
                </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"
                  />
                </div>
                {audioFiles?.map((audio: any, idx: any) => (
                  <div
                    key={idx}
                    className="flex flex-row justify-between items-center"
                  >
                    <p>Voice Note</p>
                    <Button
                      type="button"
                      onClick={() => handleDeleteAudio(idx)}
                      size="sm"
                      color="destructive"
                    >
                      X
                    </Button>
                  </div>
                ))}
                {isRecording && <p>Recording... {timer} seconds remaining</p>}{" "}
                {/* Display remaining time */}
                <div className="mt-4">
                  <Label className="">Link Berita</Label>
                  {links.map((link, index) => (
                    <div key={index} className="flex items-center gap-2 mt-2">
                      <Input
                        type="url"
                        className="border rounded p-2 w-full"
                        placeholder={`Masukkan link berita ${index + 1}`}
                        value={link}
                        onChange={(e) =>
                          handleLinkChange(index, e.target.value)
                        }
                      />
                      {links.length > 1 && (
                        <button
                          type="button"
                          className="bg-red-500 text-white px-3 py-1 rounded"
                          onClick={() => handleRemoveRow(index)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      )}
                    </div>
                  ))}
                  <Button
                    type="button"
                    size="md"
                    className="mt-2 bg-blue-500 text-white px-4 py-2 rounded"
                    onClick={handleAddRow}
                  >
                    Tambah Link
                  </Button>
                </div>
              </div>
            </div>
          </div>

          <div className="mt-4">
            <Button type="submit" color="primary">
              Submit
            </Button>
          </div>
        </form>
      </div>
    </Card>
  );
}
