"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 JoditEditor from "jodit-react";
import {
  createTask,
  getTask,
  getUserLevelForAssignments,
} from "@/service/task";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { ChevronDown, ChevronUp } from "lucide-react";
import { AudioRecorder } from "react-audio-voice-recorder";
import FileUploader from "@/components/form/shared/file-uploader";
import { Upload } from "tus-js-client";
import { error } from "@/config/swal";

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

interface FileWithPreview extends File {
  preview: string;
}

export type taskDetail = {
  id: number;
  title: string;
  fileTypeOutput: string;
  assignedToTopLevel: string;
  assignedToLevel: string;
  assignmentType: {
    id: number;
    name: string;
  };
  assignmentMainType: {
    id: number;
    name: string;
  };
  taskType: string;
  broadcastType: string;
  narration: string;
  is_active: string;
};

export default function FormTask() {
  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);

  // State for various form fields
  const [taskOutput, setTaskOutput] = useState({
    all: false,
    video: false,
    audio: false,
    image: false,
    text: false,
  });

  // const [assignmentType, setAssignmentType] = useState("mediahub");
  // const [assignmentCategory, setAssignmentCategory] = useState("publication");
  const [mainType, setMainType] = useState<string>("1");
  const [taskType, setTaskType] = useState<string>("atensi-khusus");
  const [broadcastType, setBroadcastType] = useState<string>("");
  const [type, setType] = useState<string>("1");
  const [selectedTarget, setSelectedTarget] = useState("3,4");
  const [detail, setDetail] = useState<taskDetail>();
  const [refresh] = useState(false);
  const [listDest, setListDest] = useState([]);
  const [checkedLevels, setCheckedLevels] = useState(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 [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 [platformTypeVisible, setPlatformTypeVisible] = useState(false);
  const [unitSelection, setUnitSelection] = useState({
    allUnit: false,
    mabes: false,
    polda: false,
    polres: false,
  });

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

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

  // };
  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 save = async (data: TaskSchema) => {
    const fileTypeMapping = {
      all: "1",
      video: "2",
      audio: "3",
      image: "4",
      text: "5",
    };

    const unitMapping = {
      allUnit: "0",
      mabes: "1",
      polda: "2",
      polres: "3",
    };
    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])
      .map((key) => fileTypeMapping[key as keyof typeof fileTypeMapping])
      .join(",");

    const requestData: {
      id?: number;
      title: string;
      assignedToLevel: any;
      assignmentPurpose: any;
      assignmentTypeId: string;
      fileTypeOutput: string;
      narration: string;
      platformType: string | null;
      assignmentMainTypeId: any;
      taskType: string;
      assignedToRole: string;
      broadcastType: string;
    } = {
      ...data,
      // assignmentType,
      // assignmentCategory,
      assignedToLevel: handlePoldaPolresChange(),
      assignmentPurpose: assignmentPurposeString,
      assignedToRole: selectedTarget,
      taskType: taskType,
      broadcastType: broadcastType,
      assignmentMainTypeId: mainType,
      assignmentTypeId: type,
      fileTypeOutput: selectedOutputs,
      narration: data.naration,
      platformType: "",
      title: data.title,
    };

    const response = await createTask(requestData);

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

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

    if (imageFiles?.length == 0) {
      setIsImageUploadFinish(true);
    }
    imageFiles?.map(async (item: any, index: number) => {
      await uploadResumableFile(index, String(id), item, "1", "0");
    });

    if (videoFiles?.length == 0) {
      setIsVideoUploadFinish(true);
    }
    videoFiles?.map(async (item: any, index: number) => {
      await uploadResumableFile(index, String(id), item, "2", "0");
    });

    if (textFiles?.length == 0) {
      setIsTextUploadFinish(true);
    }
    textFiles?.map(async (item: any, index: number) => {
      await uploadResumableFile(index, String(id), item, "3", "0");
    });

    if (audioFiles?.length == 0) {
      setIsAudioUploadFinish(true);
    }
    audioFiles?.map(async (item: any, index: number) => {
      await uploadResumableFile(index, String(id), item, "4", "0");
    });

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

    // Start a timer that stops the recording after 2 minutes (120 seconds)
    const countdown = setInterval(() => {
      setTimer((prevTimer) => {
        if (prevTimer <= 1) {
          clearInterval(countdown); // Stop the timer when it reaches 0
          return 0;
        }
        return prevTimer - 1;
      });
    }, 1000); // Update every second

    // Automatically stop recording after 2 minutes
    setTimeout(() => {
      if (isRecording) {
        handleStopRecording();
      }
    }, 120000); // Stop after 2 minutes (120,000 ms)
  };

  const handleStopRecording = () => {
    setIsRecording(false);
    setTimer(120); // Reset the timer to 2 minutes for the next recording
  };

  const addAudioElement = (blob: Blob) => {
    const url = URL.createObjectURL(blob);
    const audio = document.createElement("audio");
    audio.src = url;
    audio.controls = true;
    document.body.appendChild(audio);

    // Convert Blob to File
    const file = new File([blob], "voiceNote.webm", { type: "audio/webm" });
    setAudioFile(file);
  };
  const handleDeleteAudio = () => {
    // Remove the audio file by setting state to null
    setAudioFile(null);
    const audioElements = document.querySelectorAll("audio");
    audioElements.forEach((audio) => audio.remove());
  };

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

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

    const upload = new Upload(file, {
      endpoint: `${process.env.NEXT_PUBLIC_API}/assignment/file/upload`,
      retryDelays: [0, 3000, 6000, 12_000, 24_000],
      chunkSize: 20_000,
      metadata: {
        assignmentid: id,
        filename: file.name,
        filetype: file.type,
        fileTypeId: fileTypeId,
        duration: "",
        isWatermark: "true", // hardcode
      },
      onError: async (e: any) => {
        console.log("Error upload :", e);
        error(e);
      },
      onChunkComplete: (
        chunkSize: any,
        bytesAccepted: any,
        bytesTotal: any
      ) => {
        const uploadPersen = Math.floor((bytesAccepted / bytesTotal) * 100);
        // progressInfo[idx].percentage = uploadPersen;
        // counterUpdateProgress++;
        // console.log(counterUpdateProgress);
        // setProgressList(progressInfo);
        // setCounterProgress(counterUpdateProgress);
      },
      onSuccess: async () => {
        // uploadPersen = 100;
        // progressInfo[idx].percentage = 100;
        // counterUpdateProgress++;
        // setCounterProgress(counterUpdateProgress);
        successTodo();
        if (fileTypeId == "1") {
          setIsImageUploadFinish(true);
        } else if (fileTypeId == "2") {
          setIsVideoUploadFinish(true);
        }
        if (fileTypeId == "3") {
          setIsTextUploadFinish(true);
        }
        if (fileTypeId == "4") {
          setIsAudioUploadFinish(true);
        }
      },
    });

    upload.start();
  }

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

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

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

  return (
    <Card>
      <div className="px-6 py-6">
        <p className="text-lg font-semibold mb-3">Form Penugasan</p>

        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="gap-5 mb-5">
            {/* Input Title */}
            <div className="space-y-2">
              <Label>Judul</Label>
              <Controller
                control={control}
                name="title"
                render={({ field }) => (
                  <Input
                    size="md"
                    type="text"
                    value={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="flex flex-row items-center">
              <div className="mt-5">
                <Label>Tujuan Pemilihan Tugas</Label>
                <Select onValueChange={setSelectedTarget}>
                  <SelectTrigger size="md">
                    <SelectValue placeholder="Pilih" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="3,4">Semua Pengguna</SelectItem>
                    <SelectItem value="4">Kontributor</SelectItem>
                    <SelectItem value="3">Approver</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex flex-wrap gap-3 mt-5 pt-5 ml-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) =>
                        setUnitSelection({ ...unitSelection, [key]: value })
                      }
                    />
                    <Label htmlFor={key}>
                      {key.charAt(0).toUpperCase() + key.slice(1)}
                    </Label>
                  </div>
                ))}
              </div>
              <div className="mt-6 pt-5 pl-3">
                <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>
            <div className="mt-5">
              <Label>Tipe Penugasan</Label>
              <RadioGroup
                value={mainType} // State yang dipetakan ke value RadioGroup
                onValueChange={(value) => setMainType(value)}
                // value={String(mainType)}
                // onValueChange={(value) => setMainType(Number(value))}
                className="flex flex-wrap gap-3"
              >
                <RadioGroupItem value="1" id="mediahub" />
                <Label htmlFor="mediahub">Mediahub</Label>
                <RadioGroupItem value="2" id="medsos-mediahub" />
                <Label htmlFor="medsos-mediahub">Medsos Mediahub</Label>
              </RadioGroup>
            </div>
            <div className="mt-5">
              <Label>Jenis Tugas </Label>
              <RadioGroup
                value={taskType}
                onValueChange={(value) => setTaskType(String(value))}
                className="flex flex-wrap gap-3"
              >
                <RadioGroupItem value="atensi-khusus" id="khusus" />
                <Label htmlFor="atensi-khusus">Atensi Khusus</Label>
                <RadioGroupItem value="tugas-harian" id="harian" />
                <Label htmlFor="tugas-harian">Tugas Harian</Label>
              </RadioGroup>
            </div>
            {/* RadioGroup Assignment Category */}
            <div className="mt-5">
              <Label>Jenis Penugasan</Label>
              <RadioGroup
                value={type} // State yang dipetakan ke value RadioGroup
                onValueChange={(value) => setType(value)} // Mengubah nilai state ketika pilihan berubah
                className="flex flex-wrap gap-3"
              >
                <div className="flex items-center gap-2">
                  <RadioGroupItem value="1" id="publication" />
                  <Label htmlFor="publication">Publikasi</Label>
                </div>
                <div className="flex items-center gap-2">
                  <RadioGroupItem value="2" id="amplification" />
                  <Label htmlFor="amplification">Amplifikasi</Label>
                </div>
                <div className="flex items-center gap-2">
                  <RadioGroupItem value="3" id="contra" />
                  <Label htmlFor="contra">Kontra</Label>
                </div>
              </RadioGroup>
            </div>
            <div className="mt-5">
              <Label>Output Tugas</Label>
              <div className="flex flex-wrap gap-3">
                {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) =>
                        setTaskOutput({ ...taskOutput, [key]: value })
                      }
                    />
                    <Label htmlFor={key}>
                      {key.charAt(0).toUpperCase() + key.slice(1)}
                    </Label>
                  </div>
                ))}
              </div>
            </div>
            {/* <div className="mt-5">
              <Label>Broadcast </Label>
              <RadioGroup
                value={broadcastType} // Nilai terpilih diambil dari state broadcastType
                onValueChange={(value) => setBroadcastType(value)} // Mengatur nilai saat radio berubah
                className="flex flex-wrap gap-3"
              >
                <div className="flex items-center gap-2">
                  <RadioGroupItem value="all" id="all" />
                  <Label htmlFor="all">Semua</Label>
                </div>
                <div className="flex items-center gap-2">
                  <RadioGroupItem value="email" id="email" />
                  <Label htmlFor="email">Email Blast</Label>
                </div>
                <div className="flex items-center gap-2">
                  <RadioGroupItem value="whatsapp" id="whatsapp" />
                  <Label htmlFor="whatsapp">WhatsApp Blast</Label>
                </div>
              </RadioGroup>
            </div> */}
            <div className="mt-5">
              <Label>Narasi Penugasan</Label>
              <Controller
                control={control}
                name="naration"
                render={({ field: { onChange, value } }) => (
                  <JoditEditor
                    ref={editor}
                    value={value}
                    onChange={onChange}
                    className="dark:text-black"
                  />
                )}
              />
              {errors.naration?.message && (
                <p className="text-red-400 text-sm">
                  {errors.naration.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) => setImageFiles(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>Voice Note</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(files)}
                    className="mt-2"
                  />
                </div>
                {audioFile && (
                  <div className="flex flex-row justify-between items-center">
                    <p>Voice note ready to submit: {audioFile.name}</p>
                    <Button
                      type="button"
                      onClick={handleDeleteAudio}
                      size="sm"
                      color="destructive"
                    >
                      X
                    </Button>
                  </div>
                )}
                {isRecording && <p>Recording... {timer} seconds remaining</p>}{" "}
                {/* Display remaining time */}
                <div className="mt-4">
                  <Label htmlFor="voiceNoteLink">Link Berita</Label>
                  <Input
                    id="voiceNoteLink"
                    type="url"
                    placeholder="Masukkan link voice note"
                    value={voiceNoteLink}
                    onChange={(e) => setVoiceNoteLink(e.target.value)}
                  />
                </div>
              </div>
            </div>
          </div>

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