"use client";
import { useDeleteCms, useGetCmsList } from "@/hooks/queries/useCmsQueries";
import { TCms } from "@/lib/api/types/TCms";
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 useCmsTablePresenter = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isFilterModalOpen, setIsFilterModalOpen] = useState(false);
  const [currentCms, setCurrentCms] = useState<TCms | null>(null);
  const [params, setParams] = useState<Record<string, any>>({});
  const columns = ["row", "key", "created at", "actions"];
  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> = {};
    for (const [key, value] of searchParams.entries()) {
      newParams[key] = value;
    }
    setParams(newParams);
    filterFormReset(newParams);
  }, [searchParams, filterFormReset]);

  const { isPending, data } = useGetCmsList(params);

  const { mutate: deleteCms } = useDeleteCms(() => {
    setIsModalOpen(false);
    setCurrentCms(null);
  });

  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 (!currentCms?.id) return;
    deleteCms(currentCms.id);
  };
  return {
    columns,
    isPending,
    data,
    isModalOpen,
    setIsModalOpen,
    currentCms,
    setCurrentCms,
    onConfirmDelete,
    router,
    pathname,
    isFilterModalOpen,
    setIsFilterModalOpen,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
  };
};

export default useCmsTablePresenter;
