<script setup>
import { computed, 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 { useForm } from "@inertiajs/vue3";

/*
  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 },
  // kept for parity with other *CreateForm components; not used directly here
  types: { type: Array, default: () => [] },
  edit: { type: Boolean, default: false },
  id: { type: Number, default: 0 },
  // When true, force-show the auto mail opt-in even if person.client wasn't eager loaded
  isClientContext: { type: Boolean, default: false },
});

// Inertia useForm handles processing and errors for us

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

const close = () => {
  emit("close");
  // Clear validation errors and reset minimal fields after closing so the form reopens cleanly
  setTimeout(() => {
    form.clearErrors();
    form.reset("value", "label", "receive_auto_mails");
  }, 0);
};

const form = useForm({
  value: "",
  label: "",
  receive_auto_mails: false,
});

const resetForm = () => {
  form.reset("value", "label", "receive_auto_mails");
};

const create = async () => {
  form.post(route("person.email.create", props.person), {
    preserveScroll: true,
    onSuccess: () => {
      close();
      resetForm();
    },
  });
};

const update = async () => {
  form.put(route("person.email.update", { person: props.person, email_id: props.id }), {
    preserveScroll: true,
    onSuccess: () => {
      close();
      resetForm();
    },
  });
};

watch(
  () => props.show,
  (newVal) => {
    if (!newVal) {
      return;
    }
    if (props.edit && props.id) {
      const list = Array.isArray(props.person?.emails) ? props.person.emails : [];
      const email = list.find((e) => e.id === props.id);
      if (email) {
        form.value = email.value ?? email.email ?? email.address ?? "";
        form.label = email.label ?? "";
        form.receive_auto_mails = !!email.receive_auto_mails;
      } else {
        form.reset("value", "label", "receive_auto_mails");
      }
    } else {
      form.reset("value", "label", "receive_auto_mails");
    }
  }
);

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="form.errors.value"
            v-for="err in [].concat(form.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="form.errors.label"
            v-for="err in [].concat(form.errors.label || [])"
            :key="err"
            :message="err"
          />
        </div>

        <div
          v-if="props.person?.client || isClientContext"
          class="mt-3 flex items-center gap-2"
        >
          <input
            id="em_receive_auto_mails"
            type="checkbox"
            v-model="form.receive_auto_mails"
            class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
          />
          <label for="em_receive_auto_mails" class="text-sm"
            >Prejemaj samodejna e-sporočila</label
          >
        </div>

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