"use client";
import { apiDefaultParams } from "@/constants/Api_Params";
import {
  useDeleteContactUs,
  useReadAllContactUs,
} from "@/hooks/queries/useContactUsQuery";
import { useHybridPagination } from "@/hooks/useHybridPagination";
import { useTableSectionRowAnimations } from "@/hooks/useTableSectionRowAnimations";
import { TContact } from "@/lib/api/types/TContacts";
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";

export const useContactUsListPresenter = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentContact, setCurrentContact] = useState<TContact>();
  const [params, setParams] = useState<Record<string, unknown>>({});
  const columns: string[] = [
    "row",
    "Full name",
    "email",
    "status",
    "phone",
    "created at",
    "actions",
  ];
  const pathname = usePathname();
  const router = useRouter();
  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, unknown> = {
      ...apiDefaultParams,
      offset: 0,
      limit: 10,
    };
    for (const [key, value] of searchParams.entries()) {
      newParams[key] = value;
    }
    setParams(newParams);
    filterFormReset(newParams as any);
  }, [searchParams, filterFormReset]);

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

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

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

  const { mutate: deleteContactUS } = useDeleteContactUs(() =>
    setIsModalOpen(false),
  );

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

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

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

  const onConfirmDelete = () => {
    if (!currentContact) return;
    deleteContactUS(currentContact?.id);
  };
  return {
    columns,
    pathname,
    router,
    isPending,
    contacts: data?.data.contacts,
    metadata: data?.meta,
    setParams,
    shouldShowPagination,
    onConfirmDelete,
    setIsModalOpen,
    setCurrentContact,
    isModalOpen,
    currentContact,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
    pagination,
    handlePaginationChange,
  };
};
