<template>
  <div class="mb-5">
    <div class="col">
      <!-- {{ value == }} -->
      <label :for="`${name}-input`" class="form-label">{{ label }} <span v-if="errorMessage" class="text-red">({{ errorMessage }}) </span></label>
      <div class="row align-items-end">
        <div v-for="(image, index) in value" class="col-md-3 col-sm-6 col-12 mb-3" v-if="value">
          <ImageInput :key="value[index]['url']" :can-remove="value.length > 1 || index != 0"
            v-model="value[index]['url']" @remove="handleRemoveImage(index)"
            @change="(file) => handleFileChange(index, file)"></ImageInput>
        </div>
      </div>
      <div class="d-flex justify-content-end">
        <div>
          <button @click="handleAddImage" type="button" class="btn btn-primary">
            Tambah Gambar
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { useField } from "vee-validate";
import { ref } from "vue";
const emit = defineEmits(["update:modelValue", "removePhoto"]);
const props = defineProps({
  modelValue: {
    default: null,
  },
  name: {
    type: String,
    required: false,
  },
  label: {
    type: String,
    required: true,
  },
  successMessage: {
    type: String,
    default: "",
  },
  placeholder: {
    type: String,
    default: "",
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  rules: {
    default: null,
  },
});

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

const handleFileChange = (index, file) => {
  if (!value.value) {
    value.value = { id: null, url: file };
    return;
  }
  emit("removePhoto", value.value[index]['id'])
  value.value[index]['id'] = null;
  value.value[index]['url'] = file;
};

const handleAddImage = () => {
  if(!value.value) {
    value.value = [{id: null, url: null}]
    return
  }
  value.value.push({ id: null, url: null });
};

const handleRemoveImage = (index) => {
  if (!value.value) {
    return;
  }
  if (value.value[index].id) {
    emit("removePhoto", value.value[index].id)
  }
  value.value.splice(index, 1);
};
</script>
