"use client";
import { SortDirection } from "@/components/ui/tableSortContext";
import { useTableSectionRowAnimations } from "@/hooks/useTableSectionRowAnimations";
import { useDeleteCms, useGetCmsList } from "@/hooks/queries/useCmsQueries";
import { TCms } from "@/lib/api/types/TCms";
import { buildQueryString, deleteEmptyKeys } from "@/utils/shared";
import { useIsMutating } from "@tanstack/react-query";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";

const useCmsTablePresenter = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentCms, setCurrentCms] = useState<TCms | null>(null);
  const [params, setParams] = useState<Record<string, any>>({});
  const columns = ["row", "key", "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> = {};
    for (const [key, value] of searchParams.entries()) {
      newParams[key] = value;
    }
    setParams(newParams);
    filterFormReset(newParams);
  }, [searchParams, filterFormReset]);

  const { isPending, data } = useGetCmsList(params);

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

  const { mutate: deleteCms } = useDeleteCms(() => {
    setIsModalOpen(false);
    setCurrentCms(null);
  });

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

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

  const onConfirmDelete = () => {
    if (!currentCms?.id) return;
    deleteCms(currentCms.id);
  };

  /** Column label → BSON `sort_by` field. */
  const columnSortKeys: Record<string, string> = {
    key: "key",
    "created at": "created_at",
  };

  /** First-click direction per column. */
  const columnDefaultOrder: Record<string, SortDirection> = {
    key: "asc",
    "created at": "desc",
  };

  const sortBy = (params.sort_by as string) ?? "created_at";
  const sortOrder = (params.sort_order as SortDirection) ?? "desc";

  const handleSortChange = useCallback(
    (key: string, order: SortDirection) => {
      const next: Record<string, any> = {
        ...params,
        sort_by: key,
        sort_order: order,
        offset: 0,
      };
      delete next.cursor;
      const cleanedParams = deleteEmptyKeys(next);
      const queryString = buildQueryString(cleanedParams);
      router.push(`${pathname}?${queryString}`);
    },
    [params, pathname, router],
  );

  return {
    columns,
    columnSortKeys,
    columnDefaultOrder,
    sortBy,
    sortOrder,
    handleSortChange,
    isPending,
    data,
    isModalOpen,
    setIsModalOpen,
    currentCms,
    setCurrentCms,
    onConfirmDelete,
    router,
    pathname,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
  };
};

export default useCmsTablePresenter;
