import { useState, useMemo } from 'react';

export type SortDirection = 1 | -1 | 0;

export interface UseSortResult {
  sortedData: any[];
  setSortedField: (item: string, value: SortDirection) => void;
  field: string;
  direction: SortDirection;
}
export type SortData = Record<string, any>[];
export const useSort = (data: SortData): UseSortResult => {
  const [sortDataBy, setSortDataBy] = useState('');
  const [direction, setDirection] = useState<-1 | 1 | 0>(0);
  const sortedItems = useMemo(() => {
    const sortableItems = [...data];
    if (sortableItems.length === 0) {
      return [];
    }
    if (sortDataBy) {
      sortableItems.sort((a, b) => {
        if (a[sortDataBy] === null) return 1;
        if (b[sortDataBy] === null) return -1;
        if (a[sortDataBy] === null && b[sortDataBy] === null) return 0;
        return (
          a[sortDataBy]
            .toString()
            .localeCompare(b[sortDataBy].toString(), undefined, {
              numeric: true,
            }) * (direction > 0 ? 1 : -1)
        );
      });
    }
    return sortableItems;
  }, [data, direction, sortDataBy]);

  const setSortedField = (item, value) => {
    if (item === sortDataBy && value === direction) {
      setDirection(0);
      setSortDataBy('');
      return;
    }
    setDirection(value);
    setSortDataBy(item);
  };

  return {
    sortedData: sortedItems,
    setSortedField,
    field: sortDataBy,
    direction,
  };
};
