import { useState, useMemo } from "react";
import type { FilterValues } from "@/components/Filters";

const DEFAULT_PAGE = 1;
const DEFAULT_LIMIT = 10;

export const useOrderFilters = () => {
  const [filters, setFilters] = useState<FilterValues>({});
  const [currentPage, setCurrentPage] = useState(DEFAULT_PAGE);
  const [limit] = useState(DEFAULT_LIMIT);

  const apiParams = useMemo(() => {
    const params: Record<string, string | number | string[]> = {
      page: currentPage,
      limit: limit,
    };

    if (filters.search) {
      params.search = filters.search as string;
    }

    if (filters.statuses && Array.isArray(filters.statuses) && filters.statuses.length > 0) {
      params.statuses = filters.statuses as string[];
    }

    if (filters.paymentStatus) {
      params.paymentStatus = filters.paymentStatus as string;
    }

    return params;
  }, [filters, currentPage, limit]);

  const handleFiltersChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    setCurrentPage(DEFAULT_PAGE);
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  return {
    filters,
    currentPage,
    apiParams,
    handleFiltersChange,
    handlePageChange,
    limit,
  };
};
