"use client";
import { apiDefaultParams } from "@/constants/Api_Params";
import {
  useCompanyCategoriesQuery,
  useDeleteCompanyCategoryQuery,
  useToggleCompanyCategoryPublished,
} from "@/hooks/queries";
import { TCompanyCategory } from "@/lib/api";
import { deleteEmptyKeys } from "@/utils/shared";
import { useIsMutating } from "@tanstack/react-query";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";

const useCompanyCategoriesPresenter = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isFilterModalOpen, setIsFilterModalOpen] = useState(false);
  const [currentCategory, setCurrentCategory] = useState<TCompanyCategory>();
  const [params, setParams] = useState<Record<string, any>>({});
  const router = useRouter();
  const pathName = usePathname();
  const searchParams = useSearchParams();
  const isMutating = useIsMutating();

  const {
    register: filterRegister,
    handleSubmit: handleFilterSubmit,
    reset: filterFormReset,
    watch,
    setValue: setFilterValue,
  } = useForm();

  useEffect(() => {
    const newParams: Record<string, any> = {
      ...apiDefaultParams,
    };
    for (const [key, value] of searchParams.entries()) {
      newParams[key] = value;
    }
    setParams(newParams);
    filterFormReset(newParams);
  }, [searchParams, filterFormReset]);

  const { data, isLoading, isError } = useCompanyCategoriesQuery(params);
  const { mutate: deleteCategory } = useDeleteCompanyCategoryQuery(() =>
    setIsModalOpen(false),
  );
  const { mutate: togglePublished, isPending: isToggling } =
    useToggleCompanyCategoryPublished();

  const search = (data: any) => {
    const newParams = { ...params, ...data };
    const cleanedParams = deleteEmptyKeys(newParams);
    const queryString = new URLSearchParams(cleanedParams).toString();
    router.push(`${pathName}?${queryString}`);
    setIsFilterModalOpen(false);
  };

  const onConfirmDelete = () => {
    if (!currentCategory) return;
    deleteCategory(currentCategory?.id);
  };
  return {
    categories: data?.data.categories,
    isModalOpen,
    setIsModalOpen,
    isLoading,
    isError,
    pathName,
    router,
    params,
    setParams,
    currentCategory,
    togglePublished,
    isToggling,
    setCurrentCategory,
    onConfirmDelete,
    isFilterModalOpen,
    setIsFilterModalOpen,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
  };
};

export default useCompanyCategoriesPresenter;
