import {tabStore} from '@stores';
import {useReducer} from 'react';
import {createContext} from 'use-context-selector';

type State = {
  key: string;
  url: string;
  label: string;
}[];

type Action =
  | {type: 'ADD'; payload: State[0]}
  | {type: 'REMOVE'; payload: string}
  | {type: 'REMOVE_OTHER'; payload: string}
  | {type: 'REMOVE_RIGHT'; payload: string}
  | {type: 'CLEAR'}
  | {type: 'SORT'; payload: State};

const defaultTab: State[0] = {key: '-1', url: '/main', label: '首页'};

function reducer(state: State, action: Action): State {
  const {type} = action;
  const {key, dispatch: update} = tabStore.getState();

  // 防止react devtool报错
  function dispatch(key: string) {
    Promise.resolve().then(() => update(key));
  }

  switch (type) {
    case 'ADD': {
      const {payload} = action;
      setTimeout(function () {
        dispatch(payload.key);
      }, 0);

      const exist = state.find(val => val.key === payload.key);
      if (exist) {
        return state;
      }

      return [...state, payload];
    }
    case 'REMOVE': {
      const {payload} = action;
      const idx = state.findIndex(val => val.key === payload);
      if (idx < 0) return state;

      key === state[idx].key && dispatch(state[idx - 1].key);

      const nextState = [...state];
      nextState.splice(idx, 1);
      return nextState;
    }
    case 'REMOVE_OTHER': {
      const {payload} = action;
      const idx = state.findIndex(val => val.key === payload);
      if (idx < 0) return state;

      dispatch(payload);

      return [{...defaultTab}, {...state[idx]}];
    }
    case 'REMOVE_RIGHT': {
      const {payload} = action;
      const idx = state.findIndex(val => val.key === payload);
      if (idx < 0) return state;

      const {length} = state;
      const nextState = [...state];
      nextState.splice(idx + 1, length - idx - 1);

      if (nextState.findIndex(val => val.key === key) < 0) {
        dispatch(payload);
      }

      return nextState;
    }
    case 'CLEAR': {
      dispatch('-1');

      return [{...defaultTab}];
    }
    case 'SORT':
      return action.payload;
    default:
      return state;
  }
}

export function useContextReudcer() {
  return useReducer(reducer, [defaultTab]);
}

export const context = createContext<ReturnType<typeof useContextReudcer>>([
  [],
  () => null,
]);
