"use client";
import { ConfirmationModalProps } from "@/components/ui/ConfirmationModal";
import { SortDirection } from "@/components/ui/tableSortContext";
import { apiDefaultParams } from "@/constants/Api_Params";
import {
  useCompaniesQuery,
  useDeleteCompanyQuery,
} from "@/hooks/queries";
import { useHybridPagination } from "@/hooks/useHybridPagination";
import { useTableSectionRowAnimations } from "@/hooks/useTableSectionRowAnimations";
import { TCompany } 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, useRef, useState } from "react";
import { useForm } from "react-hook-form";

export const useCompanyListPresenter = () => {
  const [currentCompany, setCurrentCompany] = useState<TCompany | null>(null);
  const [modalConfig, setModalConfig] = useState<
    Partial<ConfirmationModalProps>
  >({});
  const [params, setParams] = useState<Record<string, any>>({});
  const [isModalOpen, setIsModalOpen] = useState(false);
  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);

  const columns = [
    "row",
    "name",
    "email",
    "phone",
    "country",
    "state",
    "language",
    "currency",
    "employee count",
    "actions",
  ];

  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, error, isPending, isError } = useCompaniesQuery(params);

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

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

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

  const { mutate: deleteCompany } = useDeleteCompanyQuery(() =>
    setIsModalOpen(false),
  );

  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({
      name: "",
      email: "",
      phone: "",
      currency: undefined,
      employee_count: "",
    });
    router.push(pathName);
  }, [pathName, router, filterFormReset]);

  const onConfirmDelete = () => {
    if (currentCompany) {
      deleteCompany(currentCompany.id);
    }
  };

  /** Column label → BSON `sort_by` field. */
  const columnSortKeys: Record<string, string> = {
    name: "name",
    email: "email",
    phone: "phone",
    country: "address.country",
    state: "address.state",
    language: "language",
    currency: "currency",
    "employee count": "employee_count",
  };

  /** First-click direction per column. */
  const columnDefaultOrder: Record<string, SortDirection> = {
    name: "asc",
    email: "asc",
    phone: "asc",
    country: "asc",
    state: "asc",
    language: "asc",
    currency: "asc",
    "employee count": "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],
  );

  const allCompanies = data?.data.companies ?? [];
  const metadata = data?.meta;
  return {
    allCompanies,
    onConfirmDelete,
    metadata,
    columns,
    columnSortKeys,
    columnDefaultOrder,
    sortBy,
    sortOrder,
    handleSortChange,
    pathName,
    currentCompany,
    modalConfig,
    setModalConfig,
    setCurrentCompany,
    error,
    isModalOpen,
    setIsModalOpen,
    router,
    isPending,
    isError,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
    setParams,
    shouldShowPagination,
    clearAllFilters,
    tableSectionRef,
    skeletonTbodyRef,
    dataTbodyRef,
    pagination,
    handlePaginationChange,
  };
};
