"use client";
import { apiDefaultParams } from "@/constants/Api_Params";
import { useGetNotificationHistoryQuery } from "@/hooks/queries/useNotificationQueries";
import { useHybridPagination } from "@/hooks/useHybridPagination";
import { useTableSectionRowAnimations } from "@/hooks/useTableSectionRowAnimations";
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 useNotificationHistoryTablePresenter = () => {
  const {
    register: filterRegister,
    handleSubmit,
    watch,
    setValue,
    reset: filterFormReset,
  } = useForm();
  const [params, setParams] = useState<Record<string, any>>({
    ...apiDefaultParams,
  });
  const searchParams = useSearchParams();
  const tableSectionRef = useRef<HTMLDivElement>(null);
  const skeletonTbodyRef = useRef<HTMLTableSectionElement>(null);
  const dataTbodyRef = useRef<HTMLTableSectionElement>(null);

  const { data, isLoading, isError, error } =
    useGetNotificationHistoryQuery(params);

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

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

  const shouldShowPagination =
    !isLoading && (data?.meta?.pages ?? 1) * (data?.meta?.limit ?? 10) > 10;
  const isMutating = useIsMutating();
  const columns: string[] = [
    "row",
    "title",
    "channel",
    "created at",
    "receiver",
    "message",
    "priority",
    "type",
    "seen",
    "status",
    "actions",
  ];
  const pathName = usePathname();
  const router = useRouter();

  useEffect(() => {
    const newParams: Record<string, any> = {
      ...apiDefaultParams,
      offset: 0,
      limit: 10,
    };
    for (const [key, value] of searchParams.entries()) {
      newParams[key] = value;
    }
    setParams(newParams);
    filterFormReset(newParams);
  }, [searchParams, filterFormReset]);

  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({ seen: undefined, search: "", user_id: undefined });
    router.push(pathName);
  }, [pathName, router, filterFormReset]);

  return {
    notificationHistory: data?.data,
    metadata: data?.meta,
    isLoading,
    columns,
    router,
    pathName,
    setParams,
    filterRegister,
    handleSubmit,
    handleFilterSubmit: handleSubmit,
    watch,
    setValue,
    isMutating,
    search,
    shouldShowPagination,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
    pagination,
    handlePaginationChange,
  };
};

export default useNotificationHistoryTablePresenter;
