"use client";
import { ConfirmationModalProps } from "@/components/ui/ConfirmationModal";
import { apiDefaultParams } from "@/constants/Api_Params";
import { useTendersQuery } from "@/hooks/queries";
import { TCustomer } 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 useTenderListPresenter = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isFilterModalOpen, setIsFilterModalOpen] = useState(false);
  const [currentTender, setCurrentTender] = useState<TCustomer | null>(null);
  const [modalConfig, setModalConfig] = useState<
    Partial<ConfirmationModalProps>
  >({});
  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,
      offset: 0,
      limit: 10,
    };
    for (const [key, value] of searchParams.entries()) {
      newParams[key] = value;
    }
    setParams(newParams);
    filterFormReset(newParams);
  }, [searchParams, filterFormReset]);

  const { data, error, isPending } = useTendersQuery(params);

  const search = (data: any) => {
    const newParams = { ...params, ...data, offset: 0 };
    const cleanedParams = deleteEmptyKeys(newParams);
    const queryString = new URLSearchParams(cleanedParams).toString();
    router.push(`${pathName}?${queryString}`);
    setIsFilterModalOpen(false);
  };
  const columns = [
    "row",
    "title",
    "country code",
    "submission url",
    "status",
    "actions",
  ];
  return {
    currentTender,
    columns,
    setCurrentTender,
    router,
    allTenders: data,
    error,
    isPending,
    setParams,
    data,
    pathName,
    isModalOpen,
    setIsModalOpen,
    modalConfig,
    setModalConfig,
    isFilterModalOpen,
    setIsFilterModalOpen,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
  };
};

export default useTenderListPresenter;
