"use client";
import {
  useChangeInquiryStatus,
  useDeleteInquiry,
  useGetInquiries,
} from "@/hooks/queries/useInquiryQueries";
import { TInquiries } 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 useInquiriesListPresenter = () => {
  const [isFilterModalOpen, setIsFilterModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [isChangeStatusModalOpen, setIsChangeStatusModalOpen] = useState(false);
  const [currentInquiry, setCurrentInquiry] = useState<TInquiries | null>(null);
  const [params, setParams] = useState<Record<string, any>>({});
  const columns = [
    "row",
    "company name",
    "full name",
    "phone number",
    "status",
    "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> = {
      offset: 0,
      limit: 10,
    };
    for (const [key, value] of searchParams.entries()) {
      newParams[key] = value;
    }
    setParams(newParams);
    filterFormReset(newParams);
  }, [searchParams, filterFormReset]);

  const { data, isPending } = useGetInquiries(params);
  const { mutate } = useDeleteInquiry(() => setIsDeleteModalOpen(false));
  const { mutate: changeStatus } =
    useChangeInquiryStatus(() => setIsChangeStatusModalOpen(false));

  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 deleteInquiry = () => {
    if (!currentInquiry?.id) return;
    mutate(currentInquiry.id);
  };

  const handleChangeStatus = (data: any) => {
    if (!currentInquiry?.id) return;
    changeStatus({
      id: currentInquiry.id,
      credentials: data,
    });
  };

  return {
    columns,
    inquiries: data?.data.inquiries,
    allInquiries: data,
    isFilterModalOpen,
    setIsFilterModalOpen,
    isPending,
    isDeleteModalOpen,
    setIsDeleteModalOpen,
    isChangeStatusModalOpen,
    setIsChangeStatusModalOpen,
    currentInquiry,
    setCurrentInquiry,
    deleteInquiry,
    handleChangeStatus,

    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
    setParams,
  };
};

export default useInquiriesListPresenter;
