import { ref, watch, type Ref } from "vue";

export function usePickerFieldTempStorageData<T>(
  value: Ref<T>, 
  updateValue: (d: T) => void,
  closePopup: () => void,
  emit: (name: string, d?: any) => void,
  defaultNewValue: T,
  shouldUpdateValueImmediately: boolean,
  beforeConfirm?: ((value: T) => Promise<boolean>) | undefined,
) {

  let tempSelectText = '';
  const tempValue = ref(value.value ?? defaultNewValue) as Ref<T>;
  const selectText = ref('');

  function onSelectTextChange(t: string, forceUpdate = false) {
    tempSelectText = t;
    emit('selectTextChange', t);
    if (forceUpdate)
      selectText.value = t;
  }
  function onCancel() {
    closePopup();
    emit('cancel');
  }
  async function onConfirm() {
    closePopup();
    if (beforeConfirm && await beforeConfirm(tempValue.value))
      return;
    selectText.value = tempSelectText;
    updateValue(tempValue.value);
    emit('confirm', value.value);
  }

  watch(value, (v) => {
    tempValue.value = v;
  });
  watch(tempValue, (v) => {
    emit('tempValueChange', tempValue.value);
    if (shouldUpdateValueImmediately)
      updateValue(tempValue.value);
  });


  return {
    onSelectTextChange,
    onCancel,
    onConfirm,
    selectText,
    tempValue,
  }
}