<script setup>
import { ref, watch } from 'vue';
import DialogModal from './DialogModal.vue';
import InputLabel from './InputLabel.vue';
import SectionTitle from './SectionTitle.vue';
import TextInput from './TextInput.vue';
import InputError from './InputError.vue';
import PrimaryButton from './PrimaryButton.vue';



const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  person: Object,
  types: Array,
  edit: {
    type: Boolean,
    default: false
  },
  id: {
    type: Number,
    default: 0
  }
});

const processing = ref(false);
const errors = ref({});

const emit = defineEmits(['close']);

const close = () => {
  emit('close');

  setTimeout(() => {
    errors.value = {};
  }, 500);
}

const form = ref({
  address: '',
  country: '',
  type_id: props.types[0].id,
  description: ''
});

const resetForm = () => {
  form.value = {
    address: '',
    country: '',
    type_id: props.types[0].id,
    description: ''
  };
}

const create = async () => {
   processing.value = true;
   errors.value = {};

   const data = await axios({
    method: 'post',
    url: route('person.address.create', props.person),
    data: form.value
   }).then((response) => {
    props.person.addresses.push(response.data.address);

    processing.value = false;

    close();
    resetForm();

   }).catch((reason) => {
    errors.value = reason.response.data.errors;
    processing.value = false;
   });
}

const update = async () => {
  processing.value = true;
  errors.value = {};

  const data = await axios({
    method: 'put',
    url: route('person.address.update', {person: props.person, address_id: props.id}),
    data: form.value
  }).then((response) => {
    console.log(response.data.address)
    const index = props.person.addresses.findIndex( a => a.id === response.data.address.id );
    props.person.addresses[index] = response.data.address;

    processing.value = false;

    close();
    resetForm();

  }).catch((reason) => {
    errors.value = reason.response.data.errors;
    processing.value = false;
  });
}

watch(
  () => props.id,
  ((id) => {
    if (props.edit && id !== 0){
      console.log(props.edit)
      props.person.addresses.filter((a) => {
        if(a.id === props.id){
          form.value = {
            address: a.address,
            country: a.country,
            type_id: a.type_id,
            description: a.description
          };
        }
      });
      return;
    }
    resetForm();
  })
);

const callSubmit = () => {
  if( props.edit ) {
    update();
  } else {
    create();
  }
}

</script>

<template>
  <DialogModal
    :show="show"
    @close="close"
  >
    <template #title>
      <span v-if="edit">Spremeni naslov</span>
      <span v-else>Dodaj novi naslov</span>
    </template>
    <template #content>
      <form @submit.prevent="callSubmit">
        <SectionTitle class="border-b mb-4">
            <template #title>
                Naslov
            </template>
        </SectionTitle>

        <div class="col-span-6 sm:col-span-4">
            <InputLabel for="cr_address" value="Naslov" />
            <TextInput 
                id="cr_address"
                ref="cr_addressInput"
                v-model="form.address"
                type="text"
                class="mt-1 block w-full"
                autocomplete="address"
            />
            
            <InputError v-if="errors.address !== undefined" v-for="err in errors.address" :message="err" />
        </div>
        <div class="col-span-6 sm:col-span-4">
            <InputLabel for="cr_country" value="Država" />
            <TextInput 
                id="cr_country"
                ref="cr_countryInput"
                v-model="form.country"
                type="text"
                class="mt-1 block w-full"
                autocomplete="country"
            />
            
            <InputError v-if="errors.address !== undefined" v-for="err in errors.address" :message="err" />
        </div>
        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="cr_type" value="Tip"/>
          <select
            class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
            id="cr_type"
            v-model="form.type_id"
          >
            <option v-for="type in types" :key="type.id" :value="type.id">{{ type.name }}</option>
          </select>
        </div>
        <div class="flex justify-end mt-4">

          <PrimaryButton :class="{ 'opacity-25': processing }" :disabled="processing">
              Shrani
          </PrimaryButton>
        </div>
      </form>
    </template>
  </DialogModal>
</template>