import usePostManagement from "@/hooks/usePostManagement";
import {
  addCategory,
  addTag,
  // deleteMultipleTag,
  // deleteTagById,
  getCategories,
  // getTags,
  updateCategory as updateCategoryData,
  updateTag as updateTagData,
} from "@/services/term";
import { mergeCategory } from "@/app/library/library";
import { useDispatch } from "react-redux";
import {
  addModal,
  hideModalOnIndex,
} from "@/utils/store/features/ui/modal.slice";
import Confirm from "@/components/administrator/modals/Confirm/confirm";
import { termServices } from "@/app/services/api/term.services";
import { setNotification } from "@/utils/store/features/ui/notification.slice";

export const useTerm = () => {
  const dispatch = useDispatch();
  const { execute } = usePostManagement();

  // const getPostTags = async (callback) => {
  //   execute({
  //     call: async () => {
  //       const result = await getTags();
  //       if (callback && typeof callback === "function") callback(result);
  //     },
  //     onError: "Cannot get tags post! Contact Administrator.",
  //   });
  // };

  // const getPostCategories = async (callback) => {
  //   execute({
  //     call: async () => {
  //       const result = await getCategories();
  //       if (callback && typeof callback === "function") callback(result);
  //     },
  //     onError: "Cannot get tags post! Contact Administrator.",
  //   });
  // };

  const mergeCategoryPost = (cat) => {
    const maxDepth = Math.max(
      ...cat
        .filter((category) => category?.parents)
        .map((category) => category.parents.length)
    );
    const categories = {
      parent: cat.filter((category) => category.parents.length === 0),
      children: cat.filter((category) => category.parents.length > 0),
    };

    return categories.parent.map((category) =>
      mergeCategory(category, categories.children, 0, maxDepth)
    );
  };

  const updateCategory = async (category, callback) => {
    execute({
      call: async () => {
        const result = await updateCategoryData(category);
        if (callback && typeof callback === "function") callback(result);
      },
      onSuccess: "Category updated successfully!",
      onError: "Failed to update category! Contact Administrator.",
    });
  };

  const createEmptyTag = async (callback) => {
    execute({
      call: async () => {
        const result = await addTag({});
        if (callback && typeof callback === "function") callback(result);
      },
      onSuccess: "Tag created successfully!",
      onError: "Failed to create tag! Contact Administrator.",
    });
  };

  const createMultipleTags = async (data, callback) => {
    execute({
      call: async () => {
        const result = await termServices.createMultipleTags(data);
        if (callback && typeof callback === "function") callback(result);
      },
      onSuccess: "Tag created successfully!",
      onError: "Failed to create tag! Contact Administrator.",
    });
  };

  const updateTag = async (tag, callback) => {
    execute({
      call: async () => {
        const result = await updateTagData(tag);
        if (callback && typeof callback === "function") callback(result);
      },
      onSuccess: "Tag updated successfully!",
      onError: "Failed to update tag! Contact Administrator.",
    });
  };

  const deletemultipleTag = async (ids, callback) => {
    dispatch(
      addModal({
        status: true,
        component: Confirm,
        data: {
          confirmTitle: "Delete Tags",
          confirmText: `Are you sure you want to delete ${ids.length} Tags?`,
        },
        accept: {
          text: "Delete",
          action: async (config) => {
            await execute({
              call: async () => {
                const result = await termServices.deleteMultipleTag(ids);
                if (callback && typeof callback === "function")
                  callback(result);
              },
              onError: "Deleting Tags Failed! Contact Administrator.",
              onSuccess: "Deleted Tags Successfully!",
              successAction: () => {
                dispatch(hideModalOnIndex(config?.data?.index));
              },
              errorAction: () => {
                dispatch(hideModalOnIndex(config?.data?.index));
              },
            });
          },
        },
      })
    );
  };

  const deleteTag = async (id, callback, onCancel = null) => {
    dispatch(
      addModal({
        status: true,
        component: Confirm,
        data: {
          confirmTitle: "Delete Tag",
          confirmText: `Are you sure you want to delete this Tag?`,
        },
        accept: {
          text: "Delete",
          action: async (config) => {
            await execute({
              call: async () => {
                const result = await termServices.deleteTagById(id);
                if (callback && typeof callback === "function")
                  callback(result);
              },
              onError: "Deleting Tag Failed! Contact Administrator.",
              onSuccess: "Deleted Tag Successfully!",
              successAction: () => {
                dispatch(hideModalOnIndex(config?.data?.index));
              },
              errorAction: () => {
                dispatch(hideModalOnIndex(config?.data?.index));
              },
            });
          },
        },
        close: {
          text: null,
          action: (result) => {
            if (onCancel && typeof onCancel === "function") onCancel(result);
          },
        },
      })
    );
  };

  const createEmptyCategory = async (callback) => {
    execute({
      call: async () => {
        const result = await addCategory({});
        if (callback && typeof callback === "function") callback(result);
      },
      onSuccess: "Category created successfully!",
      onError: "Failed to create category! Contact Administrator.",
    });
  };

  const deleteCategory = async (id, callback, onCancel = null) => {
    try {
      const allchildren = await termServices.getChildrenById(id);
      console.log({ allchildren });
      const removeDuplicate = Array.from(
        new Set(allchildren.map((data) => JSON.stringify(data)))
      ).map((data) => JSON.parse(data));

      dispatch(
        addModal({
          status: true,
          component: Confirm,
          data: {
            confirmTitle: "Delete Category",
            confirmText: `Are you sure you want to delete <span style="color:red; font-weight:700; margin: 0 5px">${removeDuplicate.length}</span> categories?`,
          },
          accept: {
            text: "Delete",
            action: async (config) => {
              await execute({
                call: async () => {
                  const result = await termServices.deleteCategoryById(id);
                  if (callback && typeof callback === "function")
                    callback(result);
                },
                onError: "Deleting Category Failed! Contact Administrator.",
                onSuccess: "Deleted Category Successfully!",
                successAction: () => {
                  dispatch(hideModalOnIndex(config?.data?.index));
                },
                errorAction: (e) => {
                  console.log({ e });
                  dispatch(hideModalOnIndex(config?.data?.index));
                },
              });
            },
          },
          close: {
            text: null,
            action: (result) => {
              if (onCancel && typeof onCancel === "function") onCancel(result);
            },
          },
        })
      );
    } catch (error) {
      console.log(error);
      dispatch(
        setNotification({
          status: true,
          type: "error",
          message: "Something went wrong! Contact Administrator.",
        })
      );
    }
  };

  const deleteMultipleCategory = async (ids, callback, finallyCallback) => {
    try {
      const allchildren = await termServices.getChildMultipleId(ids);
      const removeDuplicate = Array.from(
        new Set(allchildren.map((data) => JSON.stringify(data)))
      ).map((data) => JSON.parse(data));

      dispatch(
        addModal({
          status: true,
          component: Confirm,
          data: {
            confirmTitle: "Delete Category",
            confirmText: `Are you sure you want to delete <span style="color:red; font-weight:700; margin: 0 5px">${removeDuplicate.length}</span> categories?`,
          },
          accept: {
            text: "Delete",
            action: async (config) => {
              await execute({
                call: async () => {
                  const result = await termServices.deteleMultipleCategories(
                    ids
                  );
                  if (callback && typeof callback === "function")
                    callback(result);
                },
                onError: "Deleting Category Failed! Contact Administrator.",
                onSuccess: "Deleted Category Successfully!",
                successAction: () => {
                  dispatch(hideModalOnIndex(config?.data?.index));
                },
                errorAction: () => {
                  dispatch(hideModalOnIndex(config?.data?.index));
                },
              });
            },
          },
        })
      );
    } catch (error) {
      dispatch(
        setNotification({
          status: true,
          type: "error",
          message: "Something went wrong! Contact Administrator.",
        })
      );
    } finally {
      if (finallyCallback && typeof finallyCallback === "function")
        finallyCallback();
    }
  };

  return {
    // getPostTags,
    mergeCategoryPost,
    updateCategory,
    updateTag,
    deleteTag,
    createEmptyTag,
    createMultipleTags,
    deletemultipleTag,
    // getPostCategories,
    createEmptyCategory,
    deleteCategory,
    deleteMultipleCategory,
  };
};
