import { useCallback, useState } from "react";
import { useDispatch } from "react-redux";

import styles from "@/components/administrator/PostEditor/posteditor.module.css";

import { addModal } from "@/utils/store/features/ui/modal.slice";

import Input from "@/components/administrator/form/Input/input";
import InputMultiple from "@/components/administrator/form/InputMultiple/input.multiple";
import CategorySelector from "@/components/administrator/modals/CategorySelector/category.selector";

import { useTerm } from "@/hooks/useTerm";

import { RiPriceTag3Line } from "react-icons/ri";
import { TbCategory2 } from "react-icons/tb";
import { termServices } from "@/app/services/api/term.services";
import { removeDuplicateProp, slugify } from "@/app/library/library";

const Meta = ({ data, setData, other, setTerm }) => {
  const dispatch = useDispatch();
  const [lockSlug, setLockSlug] = useState(true);
  const { mergeCategoryPost, createMultipleTags } = useTerm();

  const setMultiple = useCallback(
    (data, term) =>
      setTimeout(() => setData((prev) => ({ ...prev, [term]: data }))),
    [setData]
  );

  const setTermData = useCallback(
    (data) => {
      setTerm(data);
    },
    [setTerm]
  );

  return (
    <>
      <Input
        label="Slug"
        className={styles.input}
        value={data?.slug || ""}
        labelclassname={styles.label}
        onChange={(e) =>
          setData((prev) => ({
            ...prev,
            slug: e.target.value,
          }))
        }
        format={{
          label: lockSlug ? "Unlock" : "Lock",
          changeInput: false,
          action: (element) => {
            setTimeout(() => element.focus(), 200);
            setLockSlug(!lockSlug);
          },
        }}
        disabled={lockSlug}
      />
      <InputMultiple
        label="Categories"
        labelclassname={styles.label}
        icon={<TbCategory2 />}
        display="name"
        get="_id"
        data={other.categories}
        selected={data.categories}
        onChange={(data) => setMultiple(data, "categories")}
        iconAction={async () => {
          dispatch(
            addModal({
              status: true,
              component: CategorySelector,
              acceptDisabled: false,
              results: data.categories,
              data: { categories: mergeCategoryPost(other.categories) },
              buttonShow: true,
              accept: {
                text: "Save",
                action: (_, __, ___, result) => {
                  setMultiple(result, "categories");
                  return true;
                },
              },
            })
          );
        }}
      />
      <InputMultiple
        label="Tags"
        labelclassname={styles.label}
        icon={<RiPriceTag3Line />}
        display="name"
        get="_id"
        async={true}
        asyncData={{
          init: async (ids) => {
            const response = await termServices.searchTermById(ids);
            return response.data;
          },
          call: async (keyword) => {
            const response = await termServices.getTags(
              { page: 1, limit: 100 },
              { name: 1 },
              keyword
            );
            return response.data;
          },
        }}
        createNew={{
          status: true,
          // data is string splited by comma = array
          // tags is old data or already selected = array
          // setSearchFn is function to set search value
          createNewFn: async (data, tags, setSearchFn) => {
            if (!data.length) return;

            const dataExtend = data
              .filter((item) => item)
              .map((item) => ({
                name: item,
                description: "",
                slug: slugify(item),
              }));
            const filtered = removeDuplicateProp(dataExtend, "slug");

            await createMultipleTags(filtered, (result) => {
              setMultiple([...tags, ...result.map((tag) => tag._id)], "tags");
              setSearchFn("");
            });
          },
          label: "Create new tag.",
        }}
        selected={data.tags}
        onChange={(data) => setMultiple(data, "tags")}
      />
    </>
  );
};

export default Meta;
