import { useEffect, useState } from 'react';
import { Data } from '../../types/data';
import { SortData } from './List.model';

export const sortStoryData = <T extends Data>(
  sort: SortData<T>,
  data: T[],
): T[] => {
  return data.sort((a: T, b: T) =>
    sort.direction === 'asc'
      ? a[sort.column] > b[sort.column]
        ? 1
        : a[sort.column] < b[sort.column]
        ? -1
        : 0
      : a[sort.column] > b[sort.column]
      ? -1
      : a[sort.column] < b[sort.column]
      ? 1
      : 0,
  );
};

export function useLocalSort<T extends Data>(
  data: T[],
): {
  readonly listData: T[];
  readonly sortChangedHandler: (sort: SortData<T>) => void;
} {
  useEffect(() => {
    setListData([...data]);
  }, [data]);
  const [listData, setListData] = useState<T[]>(data);

  const sortChangedHandler = (sort: SortData<T>): void => {
    const sortOrder: T[] = sortStoryData<T>(sort, listData);
    setListData([...sortOrder]);
  };

  return { listData, sortChangedHandler } as const;
}
