"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,
  createTaskTa,
  getTask,
  getTaskTa,
  getUserLevelForAssignments,
  getUserLevelForExpert,
} from "@/service/task";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  ChevronDown,
  ChevronUp,
  Dock,
  ImageIcon,
  Music,
  Trash2,
  VideoIcon,
} from "lucide-react";
import FileUploader from "../shared/file-uploader";
import { AudioRecorder } from "react-audio-voice-recorder";
import Image from "next/image";
import { Icon } from "@iconify/react/dist/iconify.js";
import WavesurferPlayer from "@wavesurfer/react";
import { getCsrfToken } from "@/service/auth";
import { Upload } from "tus-js-client";
import { error, loading } from "@/lib/swal";
import dynamic from "next/dynamic";
import { useTranslations } from "next-intl";
import { getListCompetencies } from "@/service/management-user/management-user";

const taskSchema = z.object({
  // uniqueCode: z.string().min(1, { message: "Judul diperlukan" }),
  title: z.string().min(1, { message: "Judul diperlukan" }),
  naration: z.string().min(2, {
    message: "Narasi Penugasan harus lebih dari 2 karakter.",
  }),
});

export type taskDetail = {
  id: number;
  uniqueCode: string;
  title: string;
  fileTypeOutput: string;
  assignedToRole: string;
  assignedToUsers: string;
  assignmentMainType: {
    id: number;
    name: string;
  };
  assignmentType: string;
  expertCompetencies: string;
  broadcastType: string;
  narration: string;
  attachmentUrl: string;
  is_active: string;
};

interface FileWithPreview extends File {
  preview: string;
}

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

type Url = {
  id: number;
  attachmentUrl: string;
};

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

export default function FormTaskTaEdit() {
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const editor = useRef(null);
  type TaskSchema = z.infer<typeof taskSchema>;
  const { id } = useParams() as { id: string };
  console.log(id);

  const [expertise, setExpertiseOutput] = useState({
    semua: false,
    komunikasi: false,
    hukum: false,
    bahasa: false,
    ekonomi: false,
    politik: false,
    sosiologi: false,
    ilmuadministrasipemerintah: false,
    ti: false,
  });

  const [expert, setExpertOutput] = useState({
    semua: false,
  });

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

  const t = useTranslations("Form");
  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 [voiceNoteLink, setVoiceNoteLink] = useState("");
  const [mainType, setMainType] = useState<string>("1");
  const [taskType, setTaskType] = useState<string>("atensi-khusus");
  const [broadcastType, setBroadcastType] = useState<string>(""); // untuk Tipe Penugasan
  const [type, setType] = useState<string>("1");
  const [selectedTarget, setSelectedTarget] = useState("3,4");

  const [listExpert, setListExpert] = useState<any[]>([]);
  const [userCompetencies, setUserCompetencies] = useState<any[]>([]);
  const [selectedCompetencies, setSelectedCompetencies] = useState<Set<number>>(
    new Set()
  );

  const [detail, setDetail] = useState<taskDetail>();
  const [urlInputs, setUrlInputs] = useState<Url[]>([]);
  const [refresh] = useState(false);
  const [listDest, setListDest] = useState([]); // Data Polda dan Polres
  const [checkedLevels, setCheckedLevels] = useState<Set<number>>(new Set());
  const [expandedPolda, setExpandedPolda] = useState([{}]);
  const [isLoading, setIsLoading] = useState(false);
  const [audioFile, setAudioFile] = useState<File | null>(null);
  const [isRecording, setIsRecording] = useState(false);
  const [timer, setTimer] = useState<number>(120);

  const [imageUploadedFiles, setImageUploadedFiles] = useState<FileUploaded[]>(
    []
  );
  const [videoUploadedFiles, setVideoUploadedFiles] = useState<FileUploaded[]>(
    []
  );
  const [textUploadedFiles, setTextUploadedFiles] = useState<FileUploaded[]>(
    []
  );
  const [audioUploadedFiles, setAudioUploadedFiles] = useState<FileUploaded[]>(
    []
  );

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

  const [links, setLinks] = useState<string[]>([""]);

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

  const handleExpertiseOutputChange = (
    key: keyof typeof expertise,
    value: boolean
  ) => {
    if (key === "semua") {
      const newState = {
        semua: value,
        komunikasi: value,
        hukum: value,
        bahasa: value,
        ekonomi: value,
        politik: value,
        sosiologi: value,
        ilmuadministrasipemerintah: value,
        ti: value,
      };
      setExpertiseOutput(newState);
    } else {
      const updated = {
        ...expertise,
        [key]: value,
      };

      const allChecked = ["video", "audio", "image", "text"].every(
        (k) => updated[k as keyof typeof expertise]
      );

      updated.semua = allChecked;
      setExpertiseOutput(updated);
    }
  };

  const handleExpertOutputChange = (
    key: keyof typeof expert,
    value: boolean
  ) => {
    if (key === "semua") {
      const newState = {
        semua: value,
      };
      setExpertOutput(newState);
    } else {
      const updated = {
        ...expert,
        [key]: value,
      };

      const allChecked = ["video", "audio", "image", "text"].every(
        (k) => updated[k as keyof typeof expert]
      );

      updated.semua = allChecked;
      setExpertOutput(updated);
    }
  };

  useEffect(() => {
    getDataAdditional();
  }, []);

  async function getDataAdditional() {
    const resCompetencies = await getListCompetencies();
    console.log("competency", resCompetencies);
    setUserCompetencies(resCompetencies?.data?.data);
  }

  useEffect(() => {
    async function fetchListExpert() {
      setIsLoading(true);
      try {
        const response = await getUserLevelForExpert(id);
        setListExpert(response?.data?.data);
        console.log("tenaga ahli", response?.data?.data);
      } catch (error) {
        console.error("Error fetching Polda/Polres data:", error);
      } finally {
        setIsLoading(false);
      }
    }
    fetchListExpert();
  }, []);

  useEffect(() => {
    const fetchExpertsForCompetencies = async () => {
      const allExperts: any[] = [];

      for (const compId of Array.from(selectedCompetencies)) {
        const response = await getUserLevelForExpert(compId);
        const experts = response?.data?.data || [];
        allExperts.push(...experts);
      }

      const uniqueExperts = Array.from(
        new Map(allExperts.map((e) => [e.id, e])).values()
      );

      setListExpert(uniqueExperts);
    };

    if (selectedCompetencies.size > 0) {
      fetchExpertsForCompetencies();
    } else {
      setListExpert([]);
    }
  }, [selectedCompetencies]);

  const handleCompetencyChange = async (competencyId: number) => {
    setSelectedCompetencies((prev) => {
      const updated = new Set(prev);
      if (updated.has(competencyId)) {
        updated.delete(competencyId);
      } else {
        updated.add(competencyId);
      }
      return updated;
    });
  };

  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(() => {
    async function initState() {
      if (id) {
        const response = await getTaskTa(id);
        const details = response?.data?.data;

        setDetail(details);

        if (details?.urls) {
          // Save the URLs as objects
          setUrlInputs(details.urls);
        }

        if (details?.assignedToLevel) {
          const levels: Set<number> = new Set(
            details.assignedToLevel.split(",").map((x: any) => Number(x))
          );
          setCheckedLevels(levels);
        }

        if (details?.assignedToUsers) {
          const userIds = details.assignedToUsers.split(",").map(Number);
          setCheckedLevels(new Set(userIds));
        }

        if (details?.expertCompetencies) {
          const compIds = details.expertCompetencies.split(",").map(Number);
          setSelectedCompetencies(new Set(compIds));
        }

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

        // Add more state setting here based on other fields like broadcastType, taskOutput, etc.
      }
    }
    initState();
  }, [id, refresh]);

  const handleUrlChange = (index: number, newUrl: string) => {
    setUrlInputs((prev: any) =>
      prev.map((url: any, idx: any) => (idx === index ? newUrl : url))
    );
  };

  useEffect(() => {
    if (detail?.broadcastType) {
      setBroadcastType(detail.broadcastType); // Mengatur nilai broadcastType dari API
    }
  }, [detail?.broadcastType]);

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

  useEffect(() => {
    if (detail?.expertCompetencies) {
      const outputSet = new Set(
        detail.expertCompetencies.split(",").map(String)
      );
      setExpertiseOutput({
        semua: outputSet.has("0"),
        komunikasi: outputSet.has("1"),
        hukum: outputSet.has("2"),
        bahasa: outputSet.has("3"),
        ekonomi: outputSet.has("4"),
        politik: outputSet.has("5"),
        sosiologi: outputSet.has("6"),
        ilmuadministrasipemerintah: outputSet.has("7"),
        ti: outputSet.has("8"),
      });
    }
  }, [detail?.expertCompetencies]);

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

  const successConfirm = () => {
    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
        router.push("/en/contributor/task-ta");
      }
    });
  };

  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 handlePoldaPolresChange = () => {
  //   return Array.from(checkedLevels).join(","); // Mengonversi Set ke string
  // };

  const handleUnitChange = (
    key: keyof typeof unitSelection,
    value: boolean
  ) => {
    if (key === "allUnit") {
      const newState = {
        allUnit: value,
        mabes: value,
        polda: value,
        polres: value,
        satker: value,
      };
      setUnitSelection(newState);
    } else {
      const updatedSelection = {
        ...unitSelection,
        [key]: value,
      };

      const allChecked = ["mabes", "polda", "polres", "satker"].every(
        (k) => updatedSelection[k as keyof typeof unitSelection]
      );

      updatedSelection.allUnit = allChecked;

      setUnitSelection(updatedSelection);
    }
  };

  const handleTaskOutputChange = (
    key: keyof typeof taskOutput,
    value: boolean
  ) => {
    if (key === "all") {
      const newState = {
        all: value,
        video: value,
        audio: value,
        image: value,
        text: value,
      };
      setTaskOutput(newState);
    } else {
      const updated = {
        ...taskOutput,
        [key]: value,
      };

      const allChecked = ["video", "audio", "image", "text"].every(
        (k) => updated[k as keyof typeof taskOutput]
      );

      updated.all = allChecked;
      setTaskOutput(updated);
    }
  };

  const handleExpertChange = () => {
    return Array.from(checkedLevels).join(",");
  };

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

    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(",");

    const requestData: {
      id?: any;
      title: string;
      assignedToUsers: any;
      assignmentTypeId: string;
      narration: string;
      assignmentType: string;
      assignedToRole: string;
      expertCompetencies: string;
      attachmentUrl: string[];
    } = {
      ...data,
      // assignmentType,
      // assignmentCategory,
      id: detail?.id || null,
      assignedToUsers: handleExpertChange(),
      assignedToRole: selectedTarget,
      assignmentType: taskType,
      assignmentTypeId: type,
      narration: data.naration,
      expertCompetencies: Array.from(selectedCompetencies).join(","),
      title: data.title,
      attachmentUrl: urlInputs
        .map((url: any) => url.attachmentUrl || "")
        .filter((url: string) => url.trim() !== ""),
    };

    const response = await createTaskTa(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
      );
    });

    // MySwal.fire({
    //   title: "Sukses",
    //   text: "Data berhasil disimpan.",
    //   icon: "success",
    //   confirmButtonColor: "#3085d6",
    //   confirmButtonText: "OK",
    // }).then(() => {
    //   router.push("/en/contributor/task");
    // });
  };

  const onSubmit = (data: TaskSchema) => {
    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 = () => {
    // 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 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}/assignment/file/upload`,
      headers: headers,
      retryDelays: [0, 3000, 6000, 12_000, 24_000],
      chunkSize: 20_000,
      metadata: {
        assignmentId: id,
        filename: file.name,
        contentType: file.type,
        fileTypeId: fileTypeId,
        duration,
      },
      onBeforeRequest: function (req) {
        var xhr = req.getUnderlyingObject();
        xhr.withCredentials = true;
      },
      onError: async (e: any) => {
        console.log("Error upload :", e);
        error(e);
      },
      onChunkComplete: (
        chunkSize: any,
        bytesAccepted: any,
        bytesTotal: any
      ) => {
        // const uploadPersen = Math.floor((bytesAccepted / bytesTotal) * 100);
        // progressInfo[idx].percentage = uploadPersen;
        // counterUpdateProgress++;
        // console.log(counterUpdateProgress);
        // setProgressList(progressInfo);
        // setCounterProgress(counterUpdateProgress);
      },
      onSuccess: async () => {
        // uploadPersen = 100;
        // progressInfo[idx].percentage = 100;
        // counterUpdateProgress++;
        // setCounterProgress(counterUpdateProgress);
        successTodo();
        if (fileTypeId == "1") {
          setIsImageUploadFinish(true);
        } else if (fileTypeId == "2") {
          setIsVideoUploadFinish(true);
        }
        if (fileTypeId == "3") {
          setIsTextUploadFinish(true);
        }
        if (fileTypeId == "4") {
          setIsAudioUploadFinish(true);
        }
      },
    });

    upload.start();
  }

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

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

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

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

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

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

  const handleLinkChange = (index: number, value: string) => {
    setUrlInputs((prev: any) =>
      prev.map((url: any, idx: any) => 
        idx === index ? { ...url, attachmentUrl: value } : url
      )
    );
  };

  const handleAddLink = () => {
    setUrlInputs([
      ...urlInputs,
      { id: Date.now(), attachmentUrl: "" }, // Add a new empty object
    ]);
  };

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

  return (
    <Card>
      <div className="px-6 py-6">
        <p className="text-lg font-semibold mb-3">Form Penugasan</p>
        {detail !== undefined ? (
          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="gap-5 mb-5">
              <div className="space-y-2">
                <Label>Judul</Label>
                <Controller
                  control={control}
                  name="title"
                  render={({ field }) => (
                    <Input
                      size="md"
                      type="text"
                      defaultValue={detail?.title}
                      onChange={field.onChange}
                      placeholder="Enter Title"
                    />
                  )}
                />
                {errors.title?.message && (
                  <p className="text-red-400 text-sm">{errors.title.message}</p>
                )}
              </div>
              <div className="mt-5 space-y-2">
                <Label>{t("areas-expertise", { defaultValue: "Areas Expertise" })}</Label>
                <div className="flex flex-wrap gap-4">
                  {userCompetencies?.map((item: any) => (
                    <div className="flex items-center gap-2" key={item.id}>
                      <Checkbox
                        id={`comp-${item.id}`}
                        checked={selectedCompetencies.has(item.id)}
                        onCheckedChange={() => handleCompetencyChange(item.id)}
                      />
                      <Label htmlFor={`comp-${item.id}`}>{item.name}</Label>
                    </div>
                  ))}
                </div>
              </div>
              <div className="mt-5 space-y-2">
                <Label>{t("choose-expert", { defaultValue: "Choose Expert" })}</Label>
                <div className="flex flex-wrap gap-4">
                  <Dialog>
                    <DialogTrigger asChild>
                      <Button variant="soft" size="sm" color="primary">
                        [{"Pilih Tenaga Ahli"}]
                      </Button>
                    </DialogTrigger>
                    <DialogContent className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[1500px]">
                      <DialogHeader>
                        <DialogTitle>Daftar Tenaga Ahli</DialogTitle>
                      </DialogHeader>
                      <div className="grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto">
                        {listExpert?.map((expert: any) => (
                          <div key={expert.id} className="border p-2">
                            <Label className="flex items-center">
                              <Checkbox
                                checked={checkedLevels.has(expert.id)}
                                onCheckedChange={() =>
                                  handleCheckboxChange(expert.id)
                                }
                                className="mr-3"
                              />
                              <div className="flex flex-col gap-2">
                                <div className="font-bold">
                                  {expert.fullname}
                                </div>
                                <div className="italic">
                                  ({expert.username})
                                </div>
                              </div>
                            </Label>
                          </div>
                        ))}
                      </div>
                    </DialogContent>
                  </Dialog>
                </div>
                {checkedLevels.size > 0 && (
                  <div className="mt-3">
                    <Label className="text-sm text-gray-600 mb-2 block">
                      Tenaga Ahli Terpilih ({checkedLevels.size})
                    </Label>
                    <div className="flex flex-wrap gap-2">
                      {Array.from(checkedLevels).map((expertId) => {
                        const expert = listExpert?.find(
                          (exp: any) => exp.id === expertId
                        );
                        return expert ? (
                          <div
                            key={expert.id}
                            className="inline-flex items-center gap-2 bg-blue-100 text-blue-800 text-sm font-medium px-3 py-1.5 rounded-full border border-blue-200"
                          >
                            <span>{expert.fullname}</span>
                            <button
                              type="button"
                              onClick={() => handleCheckboxChange(expert.id)}
                              className="ml-1 text-blue-600 hover:text-blue-800 hover:bg-blue-200 rounded-full p-0.5 transition-colors"
                              title="Remove expert"
                            >
                              <svg
                                className="w-3 h-3"
                                fill="currentColor"
                                viewBox="0 0 20 20"
                              >
                                <path
                                  fillRule="evenodd"
                                  d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                                  clipRule="evenodd"
                                />
                              </svg>
                            </button>
                          </div>
                        ) : null;
                      })}
                    </div>
                  </div>
                )}
              </div>

              <div className="mt-5 space-y-2">
                <Label>{t("description", { defaultValue: "Description" })}</Label>
                <Controller
                  control={control}
                  name="naration"
                  render={({ field: { onChange, value } }) => (
                    <CustomEditor
                      onChange={onChange}
                      initialData={detail?.narration || value}
                    />
                  )}
                />
                {errors.naration?.message && (
                  <p className="text-red-400 text-sm">
                    {errors.naration.message}
                  </p>
                )}
              </div>
              <div className="space-y-2.5 mt-5">
                <Label htmlFor="attachments">{t("attachment", { defaultValue: "Attachment" })}</Label>
                <div className="space-y-3">
                  <div className="space-y-2">
                    <Label>{t("audio-visual", { defaultValue: "Audio Visual" })}</Label>
                    <FileUploader
                      accept={{
                        "mp4/*": [],
                        "mov/*": [],
                      }}
                      maxSize={100}
                      label="Upload file dengan format .mp4 atau .mov."
                      onDrop={(files) => setVideoFiles(files)}
                    />
                    {videoUploadedFiles?.map((file: any, index: number) => (
                      <div>
                        <div
                          key={index}
                          className=" flex justify-between border px-3.5 py-3 my-6 rounded-md"
                        >
                          <div className="flex gap-3 items-center">
                            <div className="file-preview">
                              <VideoIcon />
                            </div>
                            <div>
                              <div className=" text-sm  text-card-foreground">
                                {file.fileName}
                              </div>
                            </div>
                          </div>

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

                          <Button
                            size="icon"
                            color="destructive"
                            variant="outline"
                            className=" border-none rounded-full"
                            onClick={() => handleRemoveFile(file)}
                          >
                            <Icon icon="tabler:x" className=" h-5 w-5" />
                          </Button>
                        </div>
                      </div>
                    ))}
                  </div>
                  <div className="space-y-2">
                    <Label>{t("text", { defaultValue: "Text" })}</Label>
                    <FileUploader
                      accept={{
                        "pdf/*": [],
                      }}
                      maxSize={100}
                      label="Upload file dengan format .pdf."
                      onDrop={(files) => setTextFiles(files)}
                    />
                    {textUploadedFiles?.map((file: any, index: number) => (
                      <div>
                        <div
                          key={index}
                          className=" flex justify-between border px-3.5 py-3 my-6 rounded-md"
                        >
                          <div className="flex gap-3 items-center">
                            <div className="file-preview">
                              <Dock />
                            </div>
                            <div>
                              <div className=" text-sm  text-card-foreground">
                                {file.fileName}
                              </div>
                            </div>
                          </div>

                          <Button
                            size="icon"
                            color="destructive"
                            variant="outline"
                            className=" border-none rounded-full"
                            onClick={() => handleRemoveFile(file)}
                          >
                            <Icon icon="tabler:x" className=" h-5 w-5" />
                          </Button>
                        </div>
                      </div>
                    ))}
                  </div>
                  <div className="space-y-2">
                    <Label>{t("audio", { defaultValue: "Audio" })}</Label>
                    <AudioRecorder
                      onRecordingComplete={addAudioElement}
                      audioTrackConstraints={{
                        noiseSuppression: true,
                        echoCancellation: true,
                      }}
                      downloadOnSavePress={true}
                      downloadFileExtension="webm"
                    />
                    <FileUploader
                      accept={{
                        "mp3/*": [],
                        "wav/*": [],
                      }}
                      maxSize={100}
                      label="Upload file dengan format .mp3 atau .wav."
                      onDrop={(files) =>
                        setAudioFiles((prev) => [...prev, ...files])
                      }
                      className="mt-2"
                    />
                    {audioUploadedFiles?.map((file: any, index: number) => (
                      <div>
                        <div
                          key={index}
                          className=" flex justify-between border px-3.5 py-3 my-6 rounded-md"
                        >
                          <div className="flex gap-3 items-center">
                            <div className="file-preview">
                              <Music />
                            </div>
                            <div>
                              <div className=" text-sm  text-card-foreground">
                                {file.fileName}
                              </div>
                            </div>
                          </div>

                          <Button
                            size="icon"
                            color="destructive"
                            variant="outline"
                            className=" border-none rounded-full"
                            onClick={() => handleRemoveFile(file)}
                          >
                            <Icon icon="tabler:x" className=" h-5 w-5" />
                          </Button>
                        </div>
                      </div>
                    ))}
                  </div>
                  {audioFile && (
                    <div className="flex flex-row justify-between items-center">
                      <p>{t("voice-note", { defaultValue: "Voice Note" })}</p>
                      <Button
                        type="button"
                        onClick={handleDeleteAudio}
                        size="sm"
                        color="destructive"
                      >
                        X
                      </Button>
                    </div>
                  )}
                  {isRecording && <p>Recording... {timer} seconds remaining</p>}{" "}
                  {/* Display remaining time */}
                  <div className="mt-4 space-y-2">
                    <h2 className="text-lg font-bold">
                      {t("news-links", { defaultValue: "News Links" })}
                    </h2>
                    {urlInputs.map((url: any, index: any) => (
                      <div
                        key={url.id}
                        className="flex items-center gap-2 mt-2"
                      >
                        <input
                          type="url"
                          className="border rounded p-2 w-full"
                          defaultValue={url.attachmentUrl}
                          onChange={(e) =>
                            handleLinkChange(index, e.target.value)
                          }
                          placeholder={`Masukkan link berita ${index + 1}`}
                        />
                      </div>
                    ))}
                    <button
                      type="button"
                      className="mt-4 bg-green-500 text-white px-4 py-2 rounded"
                      onClick={handleAddLink}
                    >
                      {t("add-links", { defaultValue: "Add Links" })}
                    </button>
                  </div>
                </div>
              </div>
            </div>

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