import { atom, useAtom } from 'jotai';
import { format } from 'date-fns';

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

interface Filter {
  field: string;
  op: string;
  value: 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_DATE_FILTER':
      return {
        ...state,
        'x-filters': [
          ...state['x-filters'].filter(f => f.field !== 'created_at'),
          {
            field: 'created_at',
            op: '>=',
            value: `${format(
              new Date(action.payload),
              'yyyy-MM-dd'
            )}T00:00:00+00:00`,
          },
          {
            field: 'created_at',
            op: '<=',
            value: `${format(
              new Date(action.payload),
              'yyyy-MM-dd'
            )}T23:59:59+00:00`,
          },
        ],
      };

    case 'SET_CLIENT_FILTER':
      if (action.payload) {
        return {
          ...state,
          'x-filters': [
            ...state['x-filters'].filter(f => f.field !== 'customer_id'),
            {
              field: 'customer_id',
              op: '=',
              value: action.payload,
            },
          ],
        };
      } else {
        return {
          ...state,
          'x-filters': state['x-filters'].filter(
            f => f.field !== 'customer_id'
          ),
        };
      }

    case 'CLEAR_CLIENT_FILTER':
      return {
        ...state,
        'x-filters': state['x-filters'].filter(f => f.field !== 'customer_id'),
      };

    case 'SET_STATUS_ORDER_FILTER':
      if (action.payload) {
        return {
          ...state,
          'x-filters': [
            ...state['x-filters'].filter(f => f.field !== 'order_status'),
            {
              field: 'order_status',
              op: '=',
              value: action.payload,
            },
          ],
        };
      } else {
        return {
          ...state,
          'x-filters': state['x-filters'].filter(
            f => f.field !== 'order_status'
          ),
        };
      }

    case 'SET_ASSIGNEE_FILTER':
      return {
        ...state,
        'x-filters':
          action.payload !== null
            ? [
                ...state['x-filters'].filter(f => f.field !== 'bjs_delivery'),
                {
                  field: 'bjs_delivery',
                  op: '=',
                  value: action.payload,
                },
              ]
            : state['x-filters'].filter(f => f.field !== 'bjs_delivery'),
      };

    case 'CLEAR_STATUS_ORDER_FILTER':
      return {
        ...state,
        'x-filters': state['x-filters'].filter(f => f.field !== 'status_id'),
      };

    //client portal
    case 'SET_SCHEDULED_RETURN_FILTER':
      if (action.payload) {
        return {
          ...state,
          'x-filters': [
            ...state['x-filters'].filter(f => f.field !== 'order_status'),
            {
              field: 'order_status',
              op: '=',
              value: action.payload,
            },
          ],
        };
      } else {
        return {
          ...state,
          'x-filters': state['x-filters'].filter(
            f => f.field !== 'order_status'
          ),
        };
      }

    case 'SET_RETURN_COMPLETED_FILTER':
      if (action.payload) {
        return {
          ...state,
          'x-filters': [
            ...state['x-filters'].filter(f => f.field !== 'order_status'),
            {
              field: 'order_status',
              op: '=',
              value: action.payload,
            },
          ],
        };
      } else {
        return {
          ...state,
          'x-filters': state['x-filters'].filter(
            f => f.field !== 'order_status'
          ),
        };
      }

    //client portal
    case 'SET_CP_DATE_FILTER': {
      let { startDate, endDate } = action.payload;

      if (!startDate || !endDate) {
        const storedDates = JSON.parse(
          localStorage.getItem('returnDate') || '{}'
        );
        startDate = startDate ?? storedDates?.startDate;
        endDate = endDate ?? storedDates?.endDate ?? startDate;
      }

      const filters = state['x-filters'].filter(f => f.field !== 'created_at');

      if (startDate === endDate) {
        filters.push({
          field: 'created_at',
          op: '=',
          value: format(new Date(startDate), 'yyyy-MM-dd'),
        });
      } else if (startDate && endDate) {
        filters.push(
          {
            field: 'created_at',
            op: '>=',
            value: format(new Date(startDate), 'yyyy-MM-dd'),
          },
          {
            field: 'created_at',
            op: '<=',
            value: format(new Date(endDate), 'yyyy-MM-dd'),
          }
        );
      }

      return {
        ...state,
        'x-filters': filters,
        'x-pagination': { ...state['x-pagination'], page: 1 },
      };
    }
    // case 'CLEAR_CLIENT':
    //   return {
    //     ...state,
    //     'x-filters': state['x-filters'].filter(f => f.field !== 'customer_id'),
    //   };

    // case 'CLEAR_STATUS_ORDER':
    //   return {
    //     ...state,
    //     'x-filters': state['x-filters'].filter(f => f.field !== 'status_id'),
    //   };

    case 'CLEAR_DATE':
      return {
        ...state,
        'x-filters': state['x-filters'].filter(f => f.field !== 'created_at'),
      };

    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,
        'x-filters': [],
      };
    default:
      return state;
  }
};

const filtersStateAtom = atom(initialState);

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