import { useState } from 'react';

export const useCustomSorter = <T>(sortedBy: SortedBy<T>) => {
  const defaultSorter = (a: T, b: T): number => {
    const [key, direction] = (sortedBy || '').split('-') as [Extract<keyof T, string>, SortDirection];
    const factor = direction === 'asc' ? 1 : -1;

    const av = a?.[key];
    const bv = b?.[key];

    const aNil = av == null;
    const bNil = bv == null;
    if (aNil && bNil) return 0;
    if (aNil) return 1;
    if (bNil) return -1;

    if (typeof av === 'number' && typeof bv === 'number') {
      return (av - bv) * factor;
    }

    if (av instanceof Date && bv instanceof Date) {
      return (av.getTime() - bv.getTime()) * factor;
    }

    return (
      String(av).localeCompare(String(bv), undefined, {
        sensitivity: 'base',
        numeric: true,
      }) * factor
    );
  };

  const [sortFunction, setSortFunction] = useState<(a: T, b: T, defaultSorter: (a: T, b: T) => number) => number>(
    () => (a: T, b: T, defaultSorter: (a: T, b: T) => number) => defaultSorter(a, b),
  );

  return { defaultSorter, sortFunction, setSortFunction };
};

export type SortDirection = 'asc' | 'desc';
export type SortKey<T> = Extract<keyof T, string> | string;
export type SortedBy<T> = `${SortKey<T>}-${SortDirection}` | null;
