<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';
import axios from 'axios';

/*
  EmailCreateForm / Email editor
  - Props mirror Phone/Address forms for consistency
  - Routes assumed: person.email.create, person.email.update
  - Adjust route names/fields to match your backend if different
*/

const props = defineProps({
  show: { type: Boolean, default: false },
  person: { type: Object, required: true },
  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 = {}; }, 300);
};

const form = ref({
  value: '',
  label: ''
});

const resetForm = () => {
  form.value = { value: '', label: '' };
};

const create = async () => {
  processing.value = true; errors.value = {};
  try {
  const { data } = await axios.post(route('person.email.create', props.person), form.value);
    if (!Array.isArray(props.person.emails)) props.person.emails = [];
    props.person.emails.push(data.email);
    processing.value = false; close(); resetForm();
  } catch (e) {
    errors.value = e?.response?.data?.errors || {}; processing.value = false;
  }
};

const update = async () => {
  processing.value = true; errors.value = {};
  try {
  const { data } = await axios.put(route('person.email.update', { person: props.person, email_id: props.id }), form.value);
    if (!Array.isArray(props.person.emails)) props.person.emails = [];
    const idx = props.person.emails.findIndex(e => e.id === data.email.id);
    if (idx !== -1) props.person.emails[idx] = data.email;
    processing.value = false; close(); resetForm();
  } catch (e) {
    errors.value = e?.response?.data?.errors || {}; processing.value = false;
  }
};

watch(
  () => props.id,
  (id) => {
    if (props.edit && id) {
      const current = (props.person.emails || []).find(e => e.id === id);
      if (current) {
        form.value = {
          value: current.value || current.email || current.address || '',
          label: current.label || ''
        };
        return;
      }
    }
    resetForm();
  },
  { immediate: true }
);

const submit = () => (props.edit ? update() : create());
</script>

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

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="em_value" value="E-pošta" />
          <TextInput id="em_value" v-model="form.value" type="email" class="mt-1 block w-full" autocomplete="email" />
          <InputError v-if="errors.value" v-for="err in errors.value" :key="err" :message="err" />
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="em_label" value="Oznaka (neobvezno)" />
          <TextInput id="em_label" v-model="form.label" type="text" class="mt-1 block w-full" autocomplete="off" />
          <InputError v-if="errors.label" v-for="err in errors.label" :key="err" :message="err" />
        </div>

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