"use client";
import { ConfirmationModalProps } from "@/components/ui/ConfirmationModal";
import {
  useCompaniesInfiniteQuery,
  useDeleteCompanyQuery,
} from "@/hooks/queries";
import useDebounce from "@/hooks/useDebounce";
import { TCompany } from "@/lib/api";
import { usePathname, useRouter } from "next/navigation";
import { ChangeEvent, useEffect, useRef, useState } from "react";
import { useInView } from "react-intersection-observer";
import { z } from "zod";

export const useCompanyListPresenter = () => {
  const deleteModal = useRef<HTMLDialogElement | null>(null);
  const { inView } = useInView({ threshold: 0.5 });
  const [currentCompany, setCurrentCompany] = useState<TCompany | null>(null);
  const [search, setSearch] = useState("");
  const [modalConfig, setModalConfig] = useState<
    Partial<ConfirmationModalProps>
  >({});
  const [params, setParams] = useState<Record<string, any>>({
    sort: "created_at",
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const router = useRouter();
  const columns = [
    "row",
    "name",
    "email",
    "phone",
    "country",
    "state",
    "city",
    "postal code",
    "language",
    "currency",
    "employee count",
    "actions",
  ];
  const pathName = usePathname();
  const debouncedSearch = useDebounce(search, 1000);
  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),
  );
  useEffect(() => {
    const result = z.string().safeParse(debouncedSearch);
    if (result.success) {
      setParams((prevParams) => ({
        ...prevParams,
      }));
    }
  }, [debouncedSearch]);
  const handleFilterChange = (e: ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
  };
  const onConfirmDelete = () => {
    if (currentCompany) {
      deleteCompany(currentCompany.id);
    }
  };
  const allCompanies = data?.pages.flatMap((page) => page.data.companies) ?? [];
  return {
    allCompanies,
    handleFilterChange,
    onConfirmDelete,
    deleteCompany,
    isFetchingNextPage,
    data,
    columns,
    pathName,
    currentCompany,
    hasNextPage,
    fetchNextPage,
    modalConfig,
    setModalConfig,
    setCurrentCompany,
    deleteModal,
    error,
    isModalOpen,
    setIsModalOpen,
    router,
    isPending,
    isError,
    search,
  };
};
