"use client";

import { useCallback, useEffect, useState, useTransition } from "react";
import { useRouter, useSearchParams, usePathname } from "next/navigation";

interface UseDataTableParams {
  defaultPerPage?: number;
}

export function useDataTable({ defaultPerPage = 15 }: UseDataTableParams = {}) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();

  const page = Number(searchParams.get("page")) || 1;
  const perPage = Number(searchParams.get("per_page")) || defaultPerPage;
  const search = searchParams.get("search") || "";
  const sort = searchParams.get("sort") || "";
  const direction = searchParams.get("direction") || "desc";

  const updateParams = useCallback(
    (updates: Record<string, string | number | null>) => {
      const params = new URLSearchParams(searchParams.toString());
      Object.entries(updates).forEach(([key, value]) => {
        if (value === null || value === "" || value === undefined) {
          params.delete(key);
        } else {
          params.set(key, String(value));
        }
      });
      // Reset to page 1 when filters change (unless we're just changing page)
      if (!("page" in updates)) {
        params.set("page", "1");
      }
      startTransition(() => {
        router.push(`${pathname}?${params.toString()}`);
      });
    },
    [searchParams, pathname, router]
  );

  const setPage = (p: number) => updateParams({ page: p });
  const setSearch = (s: string) => updateParams({ search: s || null });
  const setSort = (field: string) => {
    if (sort === field) {
      updateParams({ sort: field, direction: direction === "asc" ? "desc" : "asc" });
    } else {
      updateParams({ sort: field, direction: "desc" });
    }
  };
  const setFilter = (key: string, value: string | null) => updateParams({ [key]: value });

  return {
    page,
    perPage,
    search,
    sort,
    direction,
    isPending,
    setPage,
    setSearch,
    setSort,
    setFilter,
    updateParams,
    searchParams,
  };
}
