"use client";
import { SortDirection } from "@/components/ui/tableSortContext";
import { apiDefaultParams } from "@/constants/Api_Params";
import {
  useCompanyCategoriesQuery,
  useDeleteCompanyCategoryQuery,
  useToggleCompanyCategoryPublished,
} from "@/hooks/queries";
import { useHybridPagination } from "@/hooks/useHybridPagination";
import { useTableSectionRowAnimations } from "@/hooks/useTableSectionRowAnimations";
import { TCompanyCategory } from "@/lib/api";
import { buildQueryString, deleteEmptyKeys } from "@/utils/shared";
import { useIsMutating } from "@tanstack/react-query";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useOptimistic, useRef, useState } from "react";
import { useForm } from "react-hook-form";

type TogglePublishedOptimistic = Pick<TCompanyCategory, "id" | "published">;

const useCompanyCategoriesPresenter = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentCategory, setCurrentCategory] = useState<TCompanyCategory>();
  const [params, setParams] = useState<Record<string, any>>({});
  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> = {
      ...apiDefaultParams,
      offset: 0,
      limit: 10,
    };
    for (const [key, value] of searchParams.entries()) {
      newParams[key] = value;
    }
    setParams(newParams);
    filterFormReset(newParams);
  }, [searchParams, filterFormReset]);

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

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

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

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

  const [optimisticCategories, addOptimisticPublished] = useOptimistic<
    TCompanyCategory[],
    TogglePublishedOptimistic
  >(categories ?? [], (state, { id, published }) =>
    state.map((c) => (c.id === id ? { ...c, published } : c)),
  );
  const { mutate: deleteCategory } = useDeleteCompanyCategoryQuery(() =>
    setIsModalOpen(false),
  );
  const { mutateAsync: togglePublished } =
    useToggleCompanyCategoryPublished();

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

  const onConfirmDelete = () => {
    if (!currentCategory) return;
    deleteCategory(currentCategory?.id);
  };
  const columns = [
    "Row",
    "Title",
    "Description",
    "Created at",
    "Published",
    "Actions",
  ];

  /** Column label → BSON `sort_by` field. */
  const columnSortKeys: Record<string, string> = {
    Title: "name",
    Description: "description",
    "Created at": "created_at",
    Published: "published",
  };

  /** First-click direction per column. */
  const columnDefaultOrder: Record<string, SortDirection> = {
    Title: "asc",
    Description: "asc",
    "Created at": "desc",
    Published: "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 newParams = buildFirstPageParams({
        ...params,
        sort_by: key,
        sort_order: order,
      });
      const cleanedParams = deleteEmptyKeys(newParams);
      const queryString = buildQueryString(cleanedParams);
      router.push(`${pathName}?${queryString}`);
    },
    [buildFirstPageParams, params, pathName, router],
  );

  return {
    categories,
    optimisticCategories,
    addOptimisticPublished,
    isModalOpen,
    setIsModalOpen,
    isLoading,
    isError,
    pathName,
    router,
    columns,
    columnSortKeys,
    columnDefaultOrder,
    sortBy,
    sortOrder,
    handleSortChange,
    params,
    setParams,
    currentCategory,
    togglePublished,
    setCurrentCategory,
    onConfirmDelete,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
    metadata,
    shouldShowPagination,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
    pagination,
    handlePaginationChange,
  };
};

export default useCompanyCategoriesPresenter;
