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

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

const selectedStatus = atom<number>(0);
export function useSelectedStatus() {
  return useAtom(selectedStatus);
}

const filterApplied = atom<boolean>(false);
export function usefilterApplied() {
  return useAtom(filterApplied);
}

const today = new Date();
const currentYear = new Date().getFullYear();

const firstJanStartDate = new Date(currentYear, 0, 1);

export const displayFormattedDate = format(firstJanStartDate, 'MMM dd, yyyy');
export const formattedDate = format(firstJanStartDate, 'yyyy-MM-dd');

//last sunday
const getLastSunday = (date: any) => {
  const lastSunday = subDays(startOfWeek(date, { weekStartsOn: 1 }), 1);
  return lastSunday;
};

export const lastSundayDate = getLastSunday(today);

export const formattedLastSundayDate = format(lastSundayDate, 'yyyy-MM-dd');

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': [
    {
      field: 'date',
      op: '>=',
      value: `${format(new Date(formattedDate), 'yyyy-MM-dd')}T00:00:00+00:00`,
    },
    {
      field: 'date',
      op: '<=',
      value: `${format(
        new Date(formattedLastSundayDate),
        'yyyy-MM-dd'
      )}T23:59:59+00:00`,
    },
    { field: 'debrief_status', op: '=', value: 2 }, // ready for invoice status
    { field: 'invoice_exceptions.reset_debrief', op: '!=', value: true },
  ],
  'x-pagination': { page: 1, per_page: 20 },
};

const overviewFilterReducer = (
  state: FilterState,
  action: any
): FilterState => {
  switch (action.type) {
    case 'SET_DATE_FILTER':
      if (action.payload === null) {
        return {
          ...state,
          'x-filters': [
            ...state['x-filters'].filter(f => f.field !== 'date'), // remove date filter
          ],
        };
      } else {
        const dateFilter = [
          {
            field: 'date',
            op: '>=',
            value: `${format(
              new Date(formattedDate),
              'yyyy-MM-dd'
            )}T00:00:00+00:00`,
          },
          {
            field: 'date',
            op: '<=',
            value: `${format(
              new Date(action.payload),
              'yyyy-MM-dd'
            )}T23:59:59+00:00`,
          },
        ];
        return {
          ...state,
          'x-filters': [
            ...state['x-filters'].filter(f => f.field !== 'date'),
            ...dateFilter,
          ],
        };
      }

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

    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,
      };
    default:
      return state;
  }
};

const overviewfiltersStateAtom = atom(initialState);

export const overviewFiltersReducerAtom = atom(
  get => get(overviewfiltersStateAtom),
  (get, set, action) =>
    set(
      overviewfiltersStateAtom,
      overviewFilterReducer(get(overviewfiltersStateAtom), action)
    )
);

// CLIENT AND SUBACCOUNT FILTERS STATE

const filterReducer = (state: FilterState, action: any): FilterState => {
  switch (action.type) {
    case 'SET_DATE_FILTER':
      if (action.payload === null) {
        return {
          ...state,
          'x-filters': [
            ...state['x-filters'].filter(f => f.field !== 'date'), // remove date filter
          ],
        };
      } else {
        const dateFilter = [
          {
            field: 'date',
            op: '>=',
            value: `${format(
              new Date(formattedDate),
              'yyyy-MM-dd'
            )}T00:00:00+00:00`,
          },
          {
            field: 'date',
            op: '<=',
            value: `${format(
              new Date(action.payload),
              'yyyy-MM-dd'
            )}T23:59:59+00:00`,
          },
        ];
        return {
          ...state,
          'x-filters': [
            ...state['x-filters'].filter(f => f.field !== 'date'),
            ...dateFilter,
          ],
        };
      }
    case 'SET_CUSTOMER_FILTER':
      return {
        ...state,
        'x-filters': [
          ...state['x-filters'].filter(f => f.field !== 'customer_id'),
          { field: 'customer_id', op: 'in', value: action.payload },
        ],
      };

    case 'SET_ORDER_QUERY':
      const { isHeavyItemActive, selectedZone } = action.payload;
      let newFilters = [
        ...state['x-filters'].filter(f => f.field !== 'order_query'),
      ];

      let queryValue = [];
      if (isHeavyItemActive) {
        queryValue.push({
          field: 'order_services_detail.heavy_item',
          op: '=',
          value: true,
        });
      }
      if (selectedZone && selectedZone.length > 0) {
        queryValue.push({ field: 'zone_code', op: 'in', value: selectedZone });
      }

      if (queryValue.length > 0) {
        newFilters.push({
          field: 'order_query',
          op: '=',
          value: queryValue,
        });
      }

      return {
        ...state,
        'x-filters': newFilters,
      };

    // case 'SET_ZONE_FILTER':
    //   return {
    //     ...state,
    //     'x-filters': [
    //       ...state['x-filters'].filter(f => f.field !== 'zone_codes'),
    //       { field: 'zone_codes', op: 'in', value: action.payload },
    //     ],
    //   };
    case 'CLEAR_FILTERS':
      return {
        ...state,
      };

    case 'CLEAR_ALL_FILTERS':
      return {
        ...state,
        'x-filters': state['x-filters'].filter(f => f.field !== 'order_query'),
      };
    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,
        },
      };
    default:
      return state;
  }
};

const filtersStateAtom = atom<any>(initialState);

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