import { GamaProp, GamaPropOption } from '@win2win/shared';
import { isArray } from 'lodash';
import { Gama } from 'src/models';
import { computed, ComputedRef, isRef, MaybeRef, Ref } from 'vue';
import { useStore } from 'vuex';

export function useGamaProps(gamaNameOrId: MaybeRef<string | number> | ComputedRef<string | number | null>) {
  const getValue = (value: Ref<any> | any) => (isRef(value) ? value.value : value);
  const idValue = computed(() => getValue(gamaNameOrId));
  const store = useStore();
  const gamas = computed(() => store.getters['gamas/gamasFlat']);
  const gama = computed(() => gamas.value.find((gama: Gama) => (typeof idValue.value === 'string' ? gama.NOMBRE === idValue.value : gama.ID_GAMA === idValue.value)));
  const props = computed<GamaProp[]>(() => gama.value?.PROPS || []);

  const getSingleLabel = (options: GamaPropOption[], value: string) => {
    const option = options.find((option) => option.value === value);
    return option?.label || value;
  };

  const getLabel = (propCode: string, rawValue: string | string[]) => {
    const prop = props.value.find((prop) => prop.code === propCode);
    if (!prop?.options?.length) return String(rawValue);
    if (isArray(rawValue)) {
      return rawValue.map((v) => getSingleLabel(prop.options!, v)).join(', ');
    } else {
      return getSingleLabel(prop.options!, rawValue);
    }
  };

  return { props, getLabel };
}
