"use client";
import { ConfirmationModalProps } from "@/components/ui/ConfirmationModal";
import {
  useCompaniesInfiniteQuery,
  useDeleteCompanyQuery,
} from "@/hooks/queries";
import { TCompany } from "@/lib/api";
import { deleteEmptyKeys } from "@/utils/shared";
import { useIsMutating } from "@tanstack/react-query";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useInView } from "react-intersection-observer";

export const useCompanyListPresenter = () => {
  const deleteModal = useRef<HTMLDialogElement | null>(null);
  const { inView } = useInView({ threshold: 0.5 });
  const [currentCompany, setCurrentCompany] = useState<TCompany | null>(null);
  const [isFilterModalOpen, setIsFilterModalOpen] = useState(false);
  const [modalConfig, setModalConfig] = useState<
    Partial<ConfirmationModalProps>
  >({});
  const [params, setParams] = useState<Record<string, any>>({});
  const [isModalOpen, setIsModalOpen] = useState(false);
  const router = useRouter();
  const pathName = usePathname();
  const searchParams = useSearchParams();
  const isMutating = useIsMutating();

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

  const columns = [
    "row",
    "name",
    "email",
    "phone",
    "country",
    "state",
    "language",
    "currency",
    "employee count",
    "actions",
  ];

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

  const {
    data,
    error,
    isPending,
    isError,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useCompaniesInfiniteQuery(params);

  useEffect(() => {
    if (inView && hasNextPage && data && data.pages.length < 5) {
      fetchNextPage();
    }
  }, [inView, hasNextPage, data, fetchNextPage]);

  const { mutate: deleteCompany } = useDeleteCompanyQuery(() =>
    setIsModalOpen(false),
  );

  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 (currentCompany) {
      deleteCompany(currentCompany.id);
    }
  };
  const allCompanies = data?.pages.flatMap((page) => page.data.companies) ?? [];
  return {
    allCompanies,
    onConfirmDelete,
    deleteCompany,
    isFetchingNextPage,
    data,
    columns,
    pathName,
    currentCompany,
    hasNextPage,
    fetchNextPage,
    modalConfig,
    setModalConfig,
    setCurrentCompany,
    deleteModal,
    error,
    isModalOpen,
    setIsModalOpen,
    router,
    isPending,
    isError,
    isFilterModalOpen,
    setIsFilterModalOpen,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
  };
};
