<template>
  <div class="col">
    <label v-if="!hideLabel" :for="`${name}-input`" class="form-label">
      {{ label }}
    </label>
    <Multiselect
      v-model="value"
      :name="name"
      :placeholder="label"
      :options="fetchOptions"
      :filter-results="false"
      :min-chars="1"
      :resolve-on-load="resolveOnLoad"
      :delay="0"
      :searchable="true"
      :mode="mode != null ? mode : 'single'"
    >
    </Multiselect>
    <div class="text-red">{{ errorMessage }}</div>
  </div>
</template>
<script>
import { toRef } from "vue";
import { useField } from "vee-validate";
import Multiselect from "@vueform/multiselect";

export default {
  props: {
    resolveOnLoad: {
      default: true,
    },
    modelValue: {
      default: null,
    },
    type: {
      type: String,
      default: "text",
    },
    name: {
      type: String,
      required: false,
    },
    label: {
      type: String,
      required: true,
    },
    successMessage: {
      type: String,
      default: "",
    },
    placeholder: {
      type: String,
      default: "",
    },
    optionText: {
      type: String,
      default: null,
    },
    optionValue: {
      type: String,
      default: null,
    },
    options: {
      required: true,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    mode: {
      type: String,
      default: "single",
    },
    hideLabel: {
      default: false,
    },
  },
  components: { Multiselect },
  setup(props, ctx) {
    const name = toRef(props, "name");

    const { value, errorMessage, handleBlur } = useField(
      () => props.name,
      props.rules,
      {
        syncVModel: true,
      }
    );

    const fetchOptions = async (keyword) => {
      console.log("masuk sini");
      let data = await props.options(keyword);
      data = data.map((item) => ({
        value: item[props.optionValue],
        label: item[props.optionText],
      }));
      return data;
    };

    return {
      name,
      value,
      errorMessage,
      handleBlur,
      fetchOptions,
    };
  },
};
</script>
