"use client";
import {
  useChangeInquiryStatus,
  useDeleteInquiry,
  useGetInquiries,
} from "@/hooks/queries/useInquiryQueries";
import { useHybridPagination } from "@/hooks/useHybridPagination";
import { useTableSectionRowAnimations } from "@/hooks/useTableSectionRowAnimations";
import { TInquiries } from "@/lib/api";
import { deleteEmptyKeys } from "@/utils/shared";
import { useIsMutating } from "@tanstack/react-query";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useForm } from "react-hook-form";

const useInquiriesListPresenter = () => {
  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();

  const tableSectionRef = useRef<HTMLDivElement>(null);
  const skeletonTbodyRef = useRef<HTMLTableSectionElement>(null);
  const dataTbodyRef = useRef<HTMLTableSectionElement>(null);

  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, isError, error } = useGetInquiries(params);

  const { pagination, handlePaginationChange, buildFirstPageParams } =
    useHybridPagination({
      meta: data?.meta,
      params,
      setParams,
      isError,
      error,
    });

  useTableSectionRowAnimations(isPending, data, {
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
  });

  const shouldShowPagination =
    !isPending && (data?.meta?.pages ?? 1) * (data?.meta?.limit ?? 10) > 10;

  const { mutate } = useDeleteInquiry(() => setIsDeleteModalOpen(false));
  const { mutate: changeStatus } =
    useChangeInquiryStatus(() => setIsChangeStatusModalOpen(false));

  const search = (formData: any) => {
    const newParams = buildFirstPageParams({ ...params, ...formData });
    const cleanedParams = deleteEmptyKeys(newParams);
    const queryString = new URLSearchParams(cleanedParams).toString();
    router.push(`${pathname}?${queryString}`);
  };

  const clearAllFilters = useCallback(() => {
    filterFormReset({ q: "", status: "" });
    router.push(pathname);
  }, [pathname, router, filterFormReset]);

  const deleteInquiry = () => {
    if (!currentInquiry?.id) return;
    mutate(currentInquiry.id);
  };

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

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

    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
    setParams,
    shouldShowPagination,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
    pagination,
    handlePaginationChange,
  };
};

export default useInquiriesListPresenter;
