import { useState, useCallback } from "react";

interface SortState {
  sort: string;
  order: "asc" | "desc";
}

export default function useTableSort(
  defaultSort = "id",
  defaultOrder: "asc" | "desc" = "desc",
) {
  const [state, setState] = useState<SortState>({
    sort: defaultSort,
    order: defaultOrder,
  });
  const [userClicked, setUserClicked] = useState(false);

  const handleSort = useCallback((column: string) => {
    setUserClicked(true);
    setState((prev) => {
      if (prev.sort === column) {
        return { sort: column, order: prev.order === "asc" ? "desc" : "asc" };
      }
      return { sort: column, order: "desc" };
    });
  }, []);

  const activeSort = userClicked ? state.sort : null;

  return { sort: state.sort, order: state.order, handleSort, activeSort };
}
