"use client";

import React, { useCallback, useMemo } from "react";
import styles from "@/components/administrator/modals/CategorySelector/categoryselector.module.css";

import { useDispatch, useSelector } from "react-redux";
import {
  selectModal,
  setResultOnIndex,
} from "@/utils/store/features/ui/modal.slice";
import { unmergingCategory } from "@/app/library/library";

// icons
import { BiCategory } from "react-icons/bi";
import { IoTrashOutline } from "react-icons/io5";

export const Categories = (props) => {
  return (
    <>
      {props.data.map((item) => (
        <div
          className={styles.item}
          key={item._id}>
          <div className={styles.parent}>
            <input
              type="checkbox"
              name="category"
              id={item.slug}
              className={styles.input}
              value={item._id}
              checked={props.selected.includes(item._id)}
              onChange={(e) => {
                if (e.target.checked)
                  return props.setCategories((prev) => [...prev, item._id]);

                props.setCategories((prev) =>
                  prev.filter((id) => id !== item._id)
                );
              }}
            />
            <label
              className={styles.label}
              htmlFor={item.slug}>
              {item.name}
            </label>
          </div>
          {item.children.length > 0 && (
            <div className={styles.children}>
              <Categories
                data={item.children}
                setCategories={props.setCategories}
                selected={props.selected}
              />
            </div>
          )}
        </div>
      ))}
    </>
  );
};

const CategorySelector = (props) => {
  const dispatch = useDispatch();
  const modalData = useSelector(selectModal);

  const categories = useMemo(() => {
    return modalData[props.data.index]?.results || [];
  }, [modalData, props]);
  const setCategories = useCallback(
    (data) => {
      if (data && typeof data !== "function") return;

      dispatch(
        setResultOnIndex({ index: props.data.index, data: data(categories) })
      );
    },
    [categories, props.data, dispatch]
  );

  const allcategories = useMemo(() => {
    return unmergingCategory(props.data.categories);
  }, [props.data]);

  const cat = useMemo(() => {
    if (categories.length === 0) return categories;

    return categories.map((item) => {
      const currentCat = allcategories.find((cat) => cat._id === item);
      const parents = currentCat?.parents?.map((parent) =>
        allcategories.find((cat) => cat._id === parent)
      );

      return [currentCat, ...parents];
    });
  }, [categories, allcategories]);

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <BiCategory /> Category Selector
      </div>
      <div className={styles.content}>
        <div className={styles.content_wrapper}>
          <Categories
            data={props.data.categories}
            selected={categories}
            setCategories={setCategories}
          />
        </div>
        <div className={styles.content_body}>
          <div className={styles.content_body_header}>Categories Selected</div>
          <div className={styles.content_body_content}>
            {cat.length === 0 && <p>No category selected</p>}
            {cat.length > 0 &&
              cat.map((item, index) => {
                return (
                  <div
                    className={styles.content_body_content_item}
                    key={index}>
                    <button
                      className={styles.delete}
                      onClick={() => {
                        setCategories((prev) =>
                          prev.filter((id) => id !== item[0]._id)
                        );
                      }}>
                      <IoTrashOutline />
                    </button>
                    {Array.from(item)
                      .reverse()
                      .map((category, i) => (
                        <span
                          key={i}
                          className={styles.category_wrapper}>
                          <p className={styles.category}>{category.name}</p>
                          {i < item.length - 1 && (
                            <span className={styles.arrow}>{">"}</span>
                          )}
                        </span>
                      ))}
                  </div>
                );
              })}
          </div>
        </div>
      </div>
    </div>
  );
};

export default CategorySelector;
