"use client";
import { AddIcon, CloudUploadIcon, TimesIcon } from "@/components/icons";
import ArticleTable from "@/components/table/article-table";
import CategoriesTable from "@/components/table/master-categories/categories-table";
import generatedArticleIds from "@/store/generated-article-store";
import {
  Button,
  Card,
  Chip,
  Input,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  Textarea,
  useDisclosure,
} from "@heroui/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, useForm } from "react-hook-form";
import { Fragment, useEffect, useState } from "react";
import { getArticleByCategory } from "@/service/article";
import ReactSelect from "react-select";
import makeAnimated from "react-select/animated";
import { useDropzone } from "react-dropzone";
import { close, error, loading } from "@/config/swal";
import {
  createCategory,
  uploadCategoryThumbnail,
} from "@/service/master-categories";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";

const categorySchema = z.object({
  id: z.number(),
  label: z.string(),
  value: z.number(),
});

const createArticleSchema = z.object({
  title: z.string().min(2, {
    message: "Judul harus diisi",
  }),
  description: z.string().min(2, {
    message: "Deskripsi harus diisi",
  }),
  tags: z.array(z.string()),
  // tags: z.array(z.string()).nonempty({
  //   message: "Minimal 1 tag",
  // }),
});

interface CategoryType {
  id: number;
  label: string;
  value: number;
}

export default function MasterCategoryTable() {
  const router = useRouter();
  const MySwal = withReactContent(Swal);

  const animatedComponents = makeAnimated();
  const { isOpen, onOpen, onOpenChange, onClose } = useDisclosure();
  const [listCategory, setListCategory] = useState<CategoryType[]>([]);
  const [files, setFiles] = useState<File[]>([]);
  const [refresh, setRefresh] = useState(false);
  const [tag, setTag] = useState("");

  const formOptions = {
    resolver: zodResolver(createArticleSchema),
    defaultValues: { title: "", description: "", category: [], tags: [] },
  };

  const { getRootProps, getInputProps } = useDropzone({
    onDrop: (acceptedFiles) => {
      setFiles(acceptedFiles.map((file) => Object.assign(file)));
    },
    maxFiles: 1,
  });
  type UserSettingSchema = z.infer<typeof createArticleSchema>;
  const {
    control,
    handleSubmit,
    formState: { errors },
    setValue,
    getValues,
    watch,
    setError,
    clearErrors,
  } = useForm<UserSettingSchema>(formOptions);

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

  const fetchCategory = async () => {
    const res = await getArticleByCategory();
    if (res?.data?.data) {
      setupCategory(res?.data?.data);
    }
  };

  const setupCategory = (data: any) => {
    const temp = [];
    for (const element of data) {
      temp.push({
        id: element.id,
        label: element.title,
        value: element.id,
      });
    }
    setListCategory(temp);
  };

  const onSubmit = async (values: z.infer<typeof createArticleSchema>) => {
    console.log("values,", values);
    loading();
    const formData = {
      title: values.title,
      statusId: 1,
      parentId: 1,
      tags: values.tags.join(","),
      description: values.description,
    };

    const response = await createCategory(formData);

    if (response?.error) {
      error(response.message);
      return false;
    }
    const categoryId = response?.data?.data?.id;
    const formFiles = new FormData();

    formFiles.append("files", files[0]);
    const resFile = await uploadCategoryThumbnail(categoryId, formFiles);
    if (resFile?.error) {
      error(resFile.message);
      return false;
    }
    close();
    setRefresh(!refresh);
    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
      }
    });
  };

  const handleRemoveFile = (file: File) => {
    const uploadedFiles = files;
    const filtered = uploadedFiles.filter((i) => i.name !== file.name);
    setFiles([...filtered]);
  };

  return (
    <div className="overflow-x-hidden overflow-y-scroll">
      <div className="px-2 md:px-4 md:py-4 w-full">
        <div className="bg-white shadow-lg dark:bg-[#18181b] rounded-xl p-3">
          <Button
            size="md"
            className="bg-[#F07C00] text-white w-full lg:w-fit"
            onPress={onOpen}
          >
            Tambah Kategori
            <AddIcon />
          </Button>
          <CategoriesTable triggerRefresh={refresh} />
        </div>
      </div>
      <Modal isOpen={isOpen} onOpenChange={onOpenChange} size="3xl">
        <ModalContent>
          {() => (
            <>
              <ModalHeader className="flex flex-col gap-1">
                Kategori Baru
              </ModalHeader>
              <ModalBody>
                <form
                  onSubmit={handleSubmit(onSubmit)}
                  className="flex flex-col gap-3"
                >
                  <div className="flex flex-col gap-1">
                    <p className="text-sm">Nama Kategori</p>
                    <Controller
                      control={control}
                      name="title"
                      render={({ field: { onChange, value } }) => (
                        <Input
                          type="text"
                          id="title"
                          placeholder=""
                          label=""
                          value={value}
                          onChange={onChange}
                          labelPlacement="outside"
                          className="w-full "
                          classNames={{
                            inputWrapper: [
                              "border-1 rounded-lg",
                              "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                            ],
                          }}
                          variant="bordered"
                        />
                      )}
                    />
                    {errors?.title && (
                      <p className="text-red-400 text-sm">
                        {errors.title?.message}
                      </p>
                    )}
                  </div>
                  <div className="flex flex-col gap-1">
                    <p className="text-sm">Deskripsi</p>
                    <Controller
                      control={control}
                      name="description"
                      render={({ field: { onChange, value } }) => (
                        <Textarea
                          type="text"
                          id="description"
                          placeholder=""
                          label=""
                          value={value}
                          onChange={onChange}
                          labelPlacement="outside"
                          className="w-full "
                          classNames={{
                            inputWrapper: [
                              "border-1 rounded-lg",
                              "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                            ],
                          }}
                          variant="bordered"
                        />
                      )}
                    />
                    {errors?.title && (
                      <p className="text-red-400 text-sm">
                        {errors.title?.message}
                      </p>
                    )}
                  </div>
                  <div className="flex flex-col gap-1">
                    <p className="text-sm mt-3">Tag Terkait</p>
                    <Controller
                      control={control}
                      name="tags"
                      render={({ field: { onChange, value } }) => (
                        <Input
                          type="text"
                          id="tags"
                          placeholder=""
                          label=""
                          value={tag}
                          onValueChange={setTag}
                          startContent={
                            <div className="flex flex-row gap-1">
                              {value.map((item, index) => (
                                <Chip
                                  color="primary"
                                  key={index}
                                  className=""
                                  onClose={() => {
                                    const filteredTags = value.filter(
                                      (tag) => tag !== item
                                    );
                                    if (filteredTags.length === 0) {
                                      setError("tags", {
                                        type: "manual",
                                        message: "Tags tidak boleh kosong",
                                      });
                                    } else {
                                      clearErrors("tags");
                                      setValue(
                                        "tags",
                                        filteredTags as [string, ...string[]]
                                      );
                                    }
                                  }}
                                >
                                  {item}
                                </Chip>
                              ))}
                            </div>
                          }
                          onKeyDown={(e) => {
                            if (e.key === "Enter") {
                              if (tag.trim() !== "") {
                                setValue("tags", [...value, tag.trim()]);
                                setTag("");
                                e.preventDefault();
                              }
                            }
                          }}
                          labelPlacement="outside"
                          className="w-full h-fit"
                          classNames={{
                            inputWrapper: [
                              "border-1 rounded-lg",
                              "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                            ],
                          }}
                          variant="bordered"
                        />
                      )}
                    />
                  </div>
                  <div className="flex flex-col gap-1">
                    <p className="text-sm mt-3">Thumbnail</p>
                    {files.length < 1 && (
                      <Fragment>
                        <div {...getRootProps({ className: "dropzone" })}>
                          <input {...getInputProps()} />
                          <div className=" w-full text-center border-dashed border border-default-200 dark:border-default-300  rounded-md py-[52px] flex  items-center flex-col">
                            <CloudUploadIcon />
                            <h4 className=" text-2xl font-medium mb-1 mt-3 text-card-foreground/80">
                              Tarik file disini atau klik untuk upload.
                            </h4>
                            <div className=" text-xs text-muted-foreground">
                              ( Upload file dengan format .jpg, .jpeg, atau
                              .png. Ukuran maksimal 100mb.)
                            </div>
                          </div>
                        </div>
                      </Fragment>
                    )}

                    {files.length > 0 && (
                      <div className="flex flex-row gap-2">
                        <img
                          src={URL.createObjectURL(files[0])}
                          className="w-[30%]"
                          alt="thumbnail"
                        />
                        <Button
                          className=" border-none rounded-full"
                          variant="bordered"
                          onClick={() => handleRemoveFile(files[0])}
                        >
                          <TimesIcon />
                        </Button>
                      </div>
                    )}
                  </div>
                  <ModalFooter className="self-end grow items-end">
                    <Button color="primary" type="submit">
                      Simpan
                    </Button>
                    <Button color="danger" variant="light" onPress={onClose}>
                      Tutup
                    </Button>
                  </ModalFooter>
                </form>
              </ModalBody>
            </>
          )}
        </ModalContent>
      </Modal>
    </div>
  );
}
