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

const DEFAULT_PAGE = 1;
const DEFAULT_LIMIT = 10;

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

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

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

  const filteredData = useMemo(() => {
    return (data: unknown[]) => {
      let filtered = [...data];

      if (filters.search) {
        const searchTerm = (filters.search as string).toLowerCase();
        filtered = filtered.filter((item: unknown) => {
          const pager = item as { tableNumber?: string; message?: string };
          return (
            pager.tableNumber?.toLowerCase().includes(searchTerm) ||
            pager.message?.toLowerCase().includes(searchTerm)
          );
        });
      }

      if (filters.status && filters.status !== "") {
        filtered = filtered.filter((item: unknown) => {
          const pager = item as { status?: string };
          return pager.status === filters.status;
        });
      }

      return filtered;
    };
  }, [filters]);

  const paginatedData = useMemo(() => {
    return (data: unknown[]) => {
      const startIndex = (currentPage - 1) * limit;
      return data.slice(startIndex, startIndex + limit);
    };
  }, [currentPage, limit]);

  const totalPages = useMemo(() => {
    return (dataLength: number) => {
      return Math.ceil(dataLength / limit) || 1;
    };
  }, [limit]);

  return {
    filters,
    currentPage,
    handleFiltersChange,
    handlePageChange,
    limit,
    filteredData,
    paginatedData,
    totalPages,
  };
};
