import React from "react";
import { RootState, useAppDispatch, useAppSelector } from "store";
import NotificationI from "ui/domain/uiNotificationEntity";
import { UIStore } from "ui/domain/uiStore";
import {
  setSearchQuery,
  setSearchbarShown,
  executeSearchQuery,
  setDrawer,
  getDrawer,
  notifyAction,
  removeNotificationAction,
  removeAllNotificationsAction,
} from "./uiActions";
import { UIStoreState } from "./uiReducer";

const uiSelector = (state: RootState): UIStoreState => state.ui;

const useUIStore = (): UIStore => {
  const {
    isSearchbarShown,
    query,
    searchResult,
    isDrawerCollapsed,
    notifications,
  } = useAppSelector(uiSelector);

  const dispatch = useAppDispatch();
  /* -------------------------------- Searchbar ------------------------------- */
  const updateSearchbar = React.useCallback(
    (isShown: boolean) => setSearchbarShown(isShown)(dispatch),
    [dispatch]
  );

  const changeQuery = React.useCallback(
    (query: string) => setSearchQuery(query)(dispatch),
    [dispatch]
  );

  const executeQuery = React.useCallback(
    (query: string) => executeSearchQuery(query)(dispatch),
    [dispatch]
  );
  /* --------------------------------- Drawer --------------------------------- */
  const initDrawer = React.useCallback(() => getDrawer()(dispatch), [dispatch]);
  const drawerIs = React.useCallback(
    (payload: boolean) => setDrawer(payload)(dispatch),
    [dispatch]
  );
  /* ------------------------------ Notifications ----------------------------- */
  const notify = React.useCallback(
    (notification: NotificationI) => notifyAction(notification)(dispatch),
    [dispatch]
  );
  const removeNotification = React.useCallback(
    (uid: NotificationI["uid"]) => removeNotificationAction(uid)(dispatch),
    [dispatch]
  );
  const clearNotifications = React.useCallback(
    () => removeAllNotificationsAction()(dispatch),
    [dispatch]
  );

  return {
    /* ----------------------------- UI search props ---------------------------- */
    isSearchbarShown,
    searchbarShown: updateSearchbar,
    /* --------------------------- Global search logic -------------------------- */
    query,
    searchResult: searchResult,
    changeQuery,
    executeQuery,
    /* --------------------------------- Drawer --------------------------------- */
    isDrawerCollapsed,
    initDrawer,
    drawerIs,
    /* ------------------------------ Notifications ----------------------------- */
    notifications,
    notify,
    removeNotification,
    clearNotifications,
  };
};

export { useUIStore };
