<template>
  <b-modal
    id="modal-smtp"
    ref="modal"
    :title="$t('global.action.add')"
    @hidden="resetForm"
  >
    <b-form id="form-smtp" @submit.prevent="handleSubmit">
      <b-row>
        <b-col sm="6">
          <b-form-group
            :label="$t('pageTransfer.smtp.email')"
            label-for="smtpEmail"
          >
            <b-form-input
              id="smtpEmail"
              v-model="email"
              type="text"
              :state="getValidationState($v.email)"
              data-test-id="smtp-input-email"
              @input="$v.email.$touch()"
            />
            <b-form-invalid-feedback role="alert">
              <template v-if="!$v.email.required">
                {{ $t('global.form.fieldRequired') }}
              </template>
              <template v-if="!$v.email.email">
                {{ $t('global.form.invalidFormat') }}
              </template>
            </b-form-invalid-feedback>
          </b-form-group>
        </b-col>
      </b-row>
    </b-form>
    <template #modal-footer="{ cancel }">
      <b-button variant="secondary" @click="cancel()">
        {{ $t('global.action.cancel') }}
      </b-button>
      <b-button form="form-smtp" type="submit" variant="primary" @click="onOk">
        {{ $t('global.action.add') }}
      </b-button>
    </template>
  </b-modal>
</template>

<script>
import VuelidateMixin from '@/components/_sila/Mixins/VuelidateMixin.js';
import { email, required } from 'vuelidate/lib/validators';

export default {
  mixins: [VuelidateMixin],
  data() {
    return {
      email: null,
    };
  },
  validations() {
    return {
      email: {
        required,
        email,
      },
    };
  },
  methods: {
    handleSubmit() {
      this.$v.$touch();
      if (this.$v.$invalid) return;

      this.$emit('ok', {
        email: this.email,
      });
      this.closeModal();
    },
    closeModal() {
      this.$nextTick(() => {
        this.$refs.modal.hide();
      });
    },
    resetForm() {
      this.email = null;
      this.$v.$reset();
      this.$emit('hidden');
    },
    onOk(bvModalEvt) {
      // prevent modal close
      bvModalEvt.preventDefault();
      this.handleSubmit();
    },
  },
};
</script>

<style lang="scss" scoped>
.input-group-prepend + input {
  padding-left: 70px !important;
}
</style>
