import {create} from 'zustand';
import {useShallow} from 'zustand/react/shallow';
import {Conversation} from '@modules/chats/interfaces';

interface ChatEventsState {
  showPinLimitReached: boolean;
  setPinLimitReached: (newValue: boolean) => void;
  moreOptions: {
    isVisible: boolean;
    target: Nullable<Conversation>;
  };
  showMoreOptions: (target: Conversation) => void;
  hideMoreOptions: () => void;
}

export const useChatEvents = create<ChatEventsState>(set => ({
  showPinLimitReached: false,
  moreOptions: {
    isVisible: false,
    target: null,
  },
  setPinLimitReached: (newValue: boolean) => {
    set({showPinLimitReached: newValue});
  },
  showMoreOptions: (target: Conversation) => {
    set({moreOptions: {isVisible: true, target}});
  },
  hideMoreOptions: () => {
    set({moreOptions: {isVisible: false, target: null}});
  },
}));

export const useShowPinLimitReached = () =>
  useChatEvents(
    useShallow(
      state => [state.showPinLimitReached, state.setPinLimitReached] as const,
    ),
  );

export const setPinLimitReached = (newValue: boolean) =>
  useChatEvents.getState().setPinLimitReached(newValue);

export const showMoreOptions = (target: Conversation) =>
  useChatEvents.getState().showMoreOptions(target);

export const hideMoreOptions = () => useChatEvents.getState().hideMoreOptions();

export const useMoreOptions = () =>
  useChatEvents(
    useShallow(state => ({
      isVisible: state.moreOptions.isVisible,
      target: state.moreOptions.target,
      hide: state.hideMoreOptions,
    })),
  );
