// components/TambahIklanModal.tsx
"use client";

import * as React from "react";
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { ChevronDown, ChevronUp, Plus } from "lucide-react";
import { Card } from "@/components/ui/card";
import Image from "next/image";
import { Upload } from "tus-js-client";
import { getCsrfToken } from "@/service/auth";
import { error, loading } from "@/lib/swal";
import { format } from "date-fns";
import { getUserLevelForAssignments } from "@/service/task";
import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, useForm } from "react-hook-form";
import withReactContent from "sweetalert2-react-content";
import { useTranslations } from "next-intl";
import Swal from "sweetalert2";
import { z } from "zod";
import { DateRange } from "react-day-picker";
import { postCalendar } from "@/service/schedule/schedule";
import { id } from "date-fns/locale";
import router from "next/router";
import { postAdvertisements } from "@/service/settings/settings";
import Cookies from "js-cookie";
import { Label } from "@/components/ui/label";
import FileUploader from "../shared/file-uploader";
import { Icon } from "@/components/ui/icon";
import { close } from "@/config/swal";
import { listDataAdvertisements } from "@/service/broadcast/broadcast";
import { useRouter } from "@/i18n/routing";

const calendarSchema = z.object({
  title: z.string().min(1, { message: "Judul diperlukan" }),
  description: z.string().min(1, { message: "Judul diperlukan" }),
});

interface FileWithPreview extends File {
  preview: string;
}

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

export function TambahIklanModal() {
  const router = useRouter();
  const [open, setOpen] = React.useState(false);
  const MySwal = withReactContent(Swal);
  const t = useTranslations("Schedule");
  type CalendarSchema = z.infer<typeof calendarSchema>;
  const [eventDate, setEventDate] = React.useState<Date | null>(new Date());
  const [listDest, setListDest] = React.useState([]);
  const [checkedLevels, setCheckedLevels] = React.useState(new Set());
  const [expandedPolda, setExpandedPolda] = React.useState([{}]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [isImageUploadFinish, setIsImageUploadFinish] = React.useState(false);
  const [files, setFiles] = React.useState<FileWithPreview[]>([]);
  const [selectedPlacement, setSelectedPlacement] = React.useState<string>("");
  const [imageUploadedFiles, setImageUploadedFiles] = React.useState<
    FileUploaded[]
  >([]);
  const [imageFiles, setImageFiles] = React.useState<FileWithPreview[]>([]);
  const [date, setDate] = React.useState<DateRange | undefined>({
    from: new Date(2025, 0, 1),
  });

  const [unitSelection, setUnitSelection] = React.useState({
    semua: false,
    mabes: false,
    polda: false,
    satker: false,
    internasional: false,
  });

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<CalendarSchema>({
    resolver: zodResolver(calendarSchema),
    defaultValues: {
      description: "",
    },
  });

  const handlePlacementSelect = (value: string) => {
    setSelectedPlacement(value);
  };

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

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

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

      updatedSelection.semua = allChecked;

      setUnitSelection(updatedSelection);
    }
  };

  const toggleExpand = (poldaId: any) => {
    setExpandedPolda((prev: any) => ({
      ...prev,
      [poldaId]: !prev[poldaId],
    }));
  };

  async function fetchExistingImageAsFile(
    url: string,
    filename = "existing-image.jpg"
  ) {
    const response = await fetch(url);
    const blob = await response.blob();
    const contentType = blob.type || "image/jpeg";
    return new File([blob], filename, { type: contentType });
  }

  const save = async (data: CalendarSchema) => {
    const unitMapping = {
      allUnit: "0",
      mabes: "1",
      polda: "2",
      satker: "4",
      internasional: "5",
    };
    const assignmentToString = Object.keys(unitSelection)
      .filter((key) => unitSelection[key as keyof typeof unitSelection])
      .map((key) => unitMapping[key as keyof typeof unitMapping])
      .join(",");

    const formMedia = new FormData();
    formMedia.append("title", data.title);
    formMedia.append("placements", selectedPlacement);
    formMedia.append("description", data.description);
    formMedia.append("redirectLink", "https://new.netidhub.com");
    formMedia.append("assignedToLevel", handlePoldaPolresChange());
    formMedia.append("file", imageFiles[0]);

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

    loading();
    const response = await postAdvertisements(formMedia);
    if (response?.error) {
      error(response?.message);
      return false;
    }
    close();

    MySwal.fire({
      icon: "success",
      title: "Berhasil",
      text: "Iklan berhasil ditambahkan.",
      confirmButtonText: "OK",
    }).then(() => {
      router.push("/admin/settings/iklan");
    });

    Cookies.set("scheduleId", response?.data?.data.id, {
      expires: 1,
    });
  };

  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}/advertisements/file/upload`,
      headers: headers,
      retryDelays: [0, 3000, 6000, 12_000, 24_000],
      chunkSize: 20_000,
      metadata: {
        advertisementsId: 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);
        }
      },
    });

    upload.start();
  }

  React.useEffect(() => {
    successTodo();
  }, [isImageUploadFinish]);

  function successTodo() {
    if (isImageUploadFinish) {
      successSubmit("/in/admin/settings/iklan");
    }
  }

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

  const onSubmit = (data: CalendarSchema) => {
    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 renderFilePreview = (url: string) => {
    return (
      <Image
        width={48}
        height={48}
        alt={"file preview"}
        src={url}
        className=" rounded border p-0.5"
      />
    );
  };

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

  React.useEffect(() => {
    fetchData();
    // setPagination({
    //   pageIndex: 0,
    //   pageSize: Number(showData),
    // });
  }, []);

  const [disabledCheckbox, setDisabledCheckbox] = React.useState<string[]>([]);

  async function fetchData() {
    try {
      loading();
      const res = await listDataAdvertisements(0, "10", "");
      const data = res?.data?.data?.content;
      // const contentData = data?.content;
      const temp = data.map((a: any) => {
        if (a.placements == "left-top") {
          return "0";
        }
        if (a.placements == "left-bottom") {
          return "1";
        }
        if (a.placements == "right-top") {
          return "2";
        }
        if (a.placements == "right-bottom") {
          return "3";
        }
      });
      console.log("contentData : ", data);

      setDisabledCheckbox(temp);

      close();
    } catch (error) {
      console.error("Error fetching tasks:", error);
    }
  }
  return (
    <div>
      <Card className="px-3 py-3">
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="space-y-4">
            <div>
              <p className="font-medium">Target Area</p>
              <div className="flex flex-wrap gap-4 mt-2">
                {[
                  { label: "Kiri - 1", value: "left-top" },
                  { label: "Kiri - 2", value: "left-bottom" },
                  { label: "Kanan - 1", value: "right-top" },
                  { label: "Kanan - 2", value: "right-bottom" },
                ].map(({ label, value }, index) => (
                  <label key={value} className="flex items-center gap-2">
                    <Checkbox
                      disabled={disabledCheckbox.includes(String(index))}
                      id={value}
                      checked={selectedPlacement === value}
                      onCheckedChange={() => handlePlacementSelect(value)}
                    />
                    <span>{label}</span>
                  </label>
                ))}
              </div>
            </div>

            <div>
              <p className="font-medium">Publish Area</p>
              <div className="flex flex-row">
                <div className="flex flex-wrap gap-3 lg: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) =>
                          handleUnitChange(
                            key as keyof typeof unitSelection,
                            value as boolean
                          )
                        }
                      />
                      <Label htmlFor={key}>
                        {key.charAt(0).toUpperCase() + key.slice(1)}
                      </Label>
                    </div>
                  ))}
                </div>
                <div className=" lg:pl-3">
                  <Dialog>
                    <DialogTrigger asChild>
                      <Button variant="soft" size="sm" color="primary">
                        [{t("custom", { defaultValue: "Custom" })}]
                      </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>

            <div>
              <p className="font-medium">Nama Iklan</p>
              <Controller
                control={control}
                name="title"
                render={({ field }) => (
                  <Input
                    size={"md"}
                    type="text"
                    value={field.value}
                    onChange={field.onChange}
                    placeholder="Masukan Nama Iklan"
                  />
                )}
              />
              {errors.title?.message && (
                <p className="text-red-400 text-sm">{errors.title.message}</p>
              )}
            </div>

            <div>
              <Label>Foto</Label>
              <p className="text-xs text-red-500">
                (Warning: Foto yang di upload adalah Foto Potrait)
              </p>
              <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>
                  <Card className="mt-2">
                    <img
                      src={file.url}
                      alt="Thumbnail Gambar Utama"
                      className="w-full h-auto rounded-md"
                    />
                  </Card>
                  <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">
                        {renderFilePreview(file.url)}
                      </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>
              <p className="font-medium">Deskripsi</p>
              <Controller
                control={control}
                name="description"
                render={({ field }) => (
                  <Textarea
                    rows={3}
                    value={field.value}
                    onChange={field.onChange}
                    placeholder="Masukan Description"
                  />
                )}
              />
              {errors.description?.message && (
                <p className="text-red-400 text-sm">
                  {errors.description?.message}
                </p>
              )}
            </div>

            <div className="text-right">
              <Button
                type="submit"
                className="bg-blue-600 text-white hover:bg-blue-700"
              >
                Tambah Iklan
              </Button>
            </div>
          </div>
        </form>
      </Card>
    </div>
  );
}
