import { AnyAction } from "@reduxjs/toolkit";
import { UIStore } from "ui/domain/uiStore";
import * as actionTypes from "./uiActionTypes";

type UIStoreState = Omit<
  UIStore,
  | "searchbarShown"
  | "changeQuery"
  | "executeQuery"
  | "drawerIs"
  | "initDrawer"
  | "notify"
  | "removeNotification"
  | "clearNotifications"
>;

const INITIAL_STATE: UIStoreState = {
  isSearchbarShown: false,
  query: "",
  searchResult: undefined,
  isDrawerCollapsed: false,
  notifications: [],
};

const uiReducer = (
  state: UIStoreState = INITIAL_STATE,
  action: AnyAction
): UIStoreState => {
  switch (action.type) {
    /* -------------------------------- Searchbar ------------------------------- */
    case actionTypes.SET_SEARCHABAR_SHOWN:
      return { ...state, isSearchbarShown: action.payload };
    /* ------------------------------- Searchflow ------------------------------- */
    case actionTypes.SET_SEARCH_QUERY:
      return { ...state, query: action.payload };
    case actionTypes.RESET_SEARCH_QUERY:
      return { ...state, query: "" };
    case actionTypes.EXECUTE_SEARCH_SUCCESS:
      return { ...state, searchResult: action.payload };
    /* --------------------------------- Drawer --------------------------------- */
    case actionTypes.SET_DRAWER_SHOWN:
      return { ...state, isDrawerCollapsed: action.payload };
    /* ------------------------------ Notifications ----------------------------- */
    case actionTypes.NOTIFICATION_ADD:
      return {
        ...state,
        notifications: state.notifications.concat([action.payload]),
      };
    case actionTypes.NOTIFICATION_REMOVE:
      return {
        ...state,
        notifications: state.notifications.filter(
          (item) => item.uid !== action.payload
        ),
      };
    case actionTypes.NOTIFICATION_REMOVE_ALL:
      return { ...state, notifications: [] };
    /* --------------------------------- Default -------------------------------- */
    default:
      return state;
  }
};

export { uiReducer };
export type { UIStoreState };
