import { atom, useAtom } from 'jotai';

const date = atom(new Date());
export const usedate = () => {
  return useAtom(date);
};

interface Filter {
  field: string;
  op: string;
  value: any;
  join?: any;
}

interface Pagination {
  page: number;
  per_page: number;
}

interface FilterState {
  'x-filters': Filter[];
  'x-pagination': Pagination;
}
const initialState: FilterState = {
  'x-filters': [],
  'x-pagination': { page: 1, per_page: 50 },
};

const filterReducer = (state: FilterState, action: any): FilterState => {
  switch (action.type) {
    // case 'SET_COMP_RETURN_FILTERS':
    //   return {
    //     ...state,
    //     'x-filters': [
    //       ...state['x-filters'].filter(
    //         f => f.field !== 'customer_name' && f.field !== 'trading_as'
    //       ),
    //       {
    //         field: 'customer_name',
    //         op: 'like',
    //         value: `%${action.payload}%`,
    //         join: 'or',
    //       },
    //       {
    //         field: 'trading_as',
    //         op: 'like',
    //         value: `%${action.payload}%`,
    //         join: 'or',
    //       },
    //     ],
    //     'x-pagination': { ...state['x-pagination'], page: 1 },
    //   };

    case 'CLEAR_SEARCH':
      return {
        ...state,
        'x-filters': [...initialState['x-filters']],
        'x-pagination': { ...initialState['x-pagination'], page: 1 },
      };

    case 'CLEAR_ALL_FILTER':
      return {
        ...state,
      };

    case 'SET_PAGE':
      return {
        ...state,
        'x-pagination': {
          ...state['x-pagination'],
          page: action.payload,
        },
      };

    case 'SET_PERPAGE':
      return {
        ...state,
        'x-pagination': {
          ...state['x-pagination'],
          per_page: action.payload,
        },
      };
    case 'CLEAR_FILTERS':
      return {
        ...state,
      };

    case 'CLEAR_ALL_FILTER':
      return {
        ...state,
      };
    default:
      return state;
  }
};

const filtersStateAtom = atom(initialState);

export const overviewfiltersReducerAtom = atom(
  get => get(filtersStateAtom),
  (get, set, action) =>
    set(filtersStateAtom, filterReducer(get(filtersStateAtom), action))
);
