import { ref, onMounted, onUnmounted } from '../../adapter-vue';
import { TUIStore } from '../../TUICallService';
import { NAME, StoreName } from '../../TUICallService/const';

export function useTip() {
  const tip = ref('');
  const show = ref(true);
  const duration = ref(0);

  const handleCallTipsChange = (value) => {
    duration.value = 0;
    tip.value = value;
  };
  const handleToastInfoChange = (value) => {
    let text = value;

    if (typeof text === 'object') {
      text = value?.text;
    }

    if (text) {
      duration.value = 2000;
      tip.value = text;
    }
  };

  onMounted(() => {
    TUIStore.watch(
      StoreName.CALL,
      {
        [NAME.CALL_TIPS]: handleCallTipsChange,
      },
      {
        notifyRangeWhenWatch: NAME.MYSELF,
      },
    );
    TUIStore.watch(
      StoreName.CALL,
      {
        [NAME.TOAST_INFO]: handleToastInfoChange,
      },
    );
  });

  onUnmounted(() => {
    TUIStore.unwatch(
      StoreName.CALL,
      {
        [NAME.CALL_TIPS]: handleCallTipsChange,
        [NAME.TOAST_INFO]: handleToastInfoChange,
      },
    );
  });

  return { tip, show, duration };
}
