<template>
  <div>
    <div class="flex justify-between">
      <div class="flex items-center">
        <!-- label of input field -->
        <label v-if="label" class="block text-sm font-medium text-gray-900">
          {{ label }}
        </label>
        <!-- asterisk sign to render if field is required -->
        <p v-if="isRequired" class="ml-1 text-red-600">*</p>
      </div>
      <span v-if="hint" class="text-sm text-gray-500">{{ hint }}</span>
    </div>
    <div class="relative mt-1 rounded-md">
      <input
        type="text"
        :class="errorClasses"
        class="block w-full flex-1 rounded-md px-3 py-2 text-gray-900 disabled:opacity-50 disabled:cursor-not-allowed focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
        :placeholder="placeholder"
        :value="email"
        :id="id"
        :disabled="disabled"
        @blur="checkValidation"
        @input="$emit('input', $event.target.value)"
      />
      <div
        v-if="isValidate"
        class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-red-600"
      >
        <c-icon name="exclamation-circle" type="solid" class="h-5 w-5"></c-icon>
      </div>
    </div>
    <p v-if="isValidate" class="mt-2 text-sm text-red-600">
      Please enter valid email address
    </p>
    <p
      v-if="helpText && isValidate == false"
      class="mt-2 text-sm text-gray-500"
    >
      {{ helpText }}
    </p>
  </div>
</template>

<script>
import CIcon from "../CIcon/CIcon.vue";
export default {
  name: "CInputEmail",
  components: { CIcon },
  props: {
    id: {
      type: String,
    },
    label: {
      type: String,
      required: true,
    },
    placeholder: {
      type: String,
    },
    hint: { type: String },
    helpText: {
      type: String,
    },
    // v-model of the field
    value: {
      type: String,
    },
    // whether the email field is mandatory or not
    isRequired: {
      type: Boolean,
    },
    disabled: {
      type: Boolean,
    },
  },
  data() {
    return {
      email: this.value,
      isValidate: false,
    };
  },
  computed: {
    errorClasses() {
      return {
        "border-red-300 text-red-900 placeholder-red-300 focus:ring-red-500 focus:border-red-500":
          this.isValidate == true,
        "border-gray-300": this.isValidate == false,
      };
    },
  },
  methods: {
    checkValidation() {
      this.isValidate =
        /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(this.email) ||
        this.email == ""
          ? false
          : true;
    },
  },
  watch: {
    value() {
      this.email = this.value;
    },
  },
};
</script>
