"use client";
import { apiDefaultParams } from "@/constants/Api_Params";
import { useGetFeedback } from "@/hooks/queries";
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";

interface IProps {
  id: string;
  paramKey: "tender_id" | "company_id" | "customer_id";
}

const useFeedbackTablePresenter = ({ id, paramKey }: IProps) => {
  const [params, setParams] = useState<Record<string, unknown>>({});
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathName = usePathname();
  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 queryParams = useMemo(
    () => ({ ...params, [paramKey]: id }),
    [params, paramKey, id],
  );

  const { data, isLoading, isError, error } = useGetFeedback(queryParams);

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

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

  const columns = [
    "row",
    "feedback type",
    "updated at",
    "created at",
    "actions",
  ];

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

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

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

  const getShowcaseSectionTitle = () => {
    if (paramKey === "tender_id") {
      const title = data?.data?.[0]?.tender?.title;
      return title ? `: ${title}` : "";
    }
    return "";
  };
  return {
    isLoading,
    feedback: Array.isArray(data?.data) ? data?.data : [],
    columns,
    pathName,
    router,
    getShowcaseSectionTitle,
    metadata: data?.meta,
    setParams,
    shouldShowPagination,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
    pagination,
    handlePaginationChange,
    isMutating,
  };
};

export default useFeedbackTablePresenter;
