<template>
  <div class="ka-call-module">
    <ka-form v-if="!isSuccessful" @submit="callMe">
      <ma-stack space="xsmall">
        <ma-text size="small" data-testid="ka-call-module__phone-label">
          <span v-markdown="$t('phoneLabel')" />
        </ma-text>
        <ka-form-field
          class="call-me"
          :placeholder="`${$t('phonePlaceholder')}`"
          is-required
          hide-asterisk
          :validators="[validators.checkPhoneNumber, validatePhone]"
          v-model="phone"
        />
        <ka-legal-checkbox
          v-model="hasAcceptedLegal"
          hide-asterisk
          size="xsmall"
        />
        <ma-button
          class="button"
          type="submit"
          :loading="isLoading"
          :text="$t('button')"
        />

        <ma-alert
          v-if="hasFeedbackError"
          tone="red"
          :title="$t('feedbackMessageError')"
          :text="$t('feedbackMessageErrorBold')"
        >
          <i18n path="feedbackMessageErrorBold">
            <a
              slot="phone"
              :href="`tel:${businessUnit.phone}`"
              class="hl-link"
              target="_top"
              v-text="businessUnit.phone"
            />
          </i18n>
        </ma-alert>
      </ma-stack>
    </ka-form>
    <ma-stack v-if="isSuccessful" space="small">
      <ma-alert tone="green" :title="$t('feedbackMessage')">
        {{ $t('feedbackMessageBold') }}
      </ma-alert>
    </ma-stack>
    <slot :phone="businessUnit.phone" name="phone" />
  </div>
</template>

<script lang="ts">
import { PropType } from 'vue'
import validators from '@kalimotxo/ui/components/KaForm/_validators/validators'
import { dataLayerPush } from '@kalimotxo/ui/utils/push-event'
import KaForm from '../KaForm/KaForm.vue'
import KaFormField from '../KaForm/_components/KaFormField.vue'
import { handleCreatePhoneLead } from '@kalimotxo/application/CallMe/createPhoneLead'
import {
  type BusinessUnit,
  type BusinessUnitType,
  businessUnits,
} from '@kalimotxo/domain/business-unit/business-unit'
import KaLegalCheckbox from '../KaLegalCheckbox/KaLegalCheckbox.vue'

const notificationTimeMs = 7000

interface ErrorType {
  response?: {
    data?: {
      message?: { details: { phone: string } }
      error?: { message: string }
    }
  }
}

export default {
  components: { KaForm, KaFormField, KaLegalCheckbox },
  props: {
    businessUnitName: {
      type: String as PropType<BusinessUnitType>,
      validator: (v: string) => Object.keys(businessUnits).includes(v),
      default: 'default',
    },
    eventCategory: { type: String, required: true },
    eventLabel: { type: String, required: true },
    referer: { type: String, default: '' },
  },
  data() {
    return {
      phone: '',
      hasAcceptedLegal: false,
      isSuccessful: false,
      isLoading: false,
      isWorkTime: false,
      hasFeedbackError: false,
      hasPhoneError: false,
    }
  },
  computed: {
    businessUnit(): BusinessUnit {
      return businessUnits[this.businessUnitName] as BusinessUnit
    },
    validators() {
      return validators
    },
    url() {
      return this.referer || location.href
    },
  },
  async created() {
    const isWorkTime = await this.$isWorkTime
    this.isWorkTime =
      isWorkTime[this.businessUnitName as keyof typeof isWorkTime]
  },
  watch: {
    phone() {
      this.hasPhoneError = false
    },
  },
  methods: {
    async callMe() {
      this.hasFeedbackError = false
      this.hasPhoneError = false
      await this.createLead()
    },
    async createLead(): Promise<void> {
      this.isLoading = true
      await handleCreatePhoneLead().execute(
        {
          phone: this.phone,
          url: this.url,
          isCallMeBack: !this.isWorkTime,
          businessUnit: this.businessUnitName,
        },
        {
          respondWithSuccess: () => {
            this.sendGtmEvent()
            this.isSuccessful = true
            setTimeout(() => (this.isSuccessful = false), notificationTimeMs)
          },
          respondWithError: (error: unknown) => {
            const errorResponse = error as ErrorType
            if (
              errorResponse?.response?.data?.message?.details?.phone ||
              errorResponse?.response?.data?.error?.message?.includes(
                'not a valid phone',
              )
            ) {
              this.hasPhoneError = true
            } else {
              this.hasFeedbackError = true
            }
            this.isSuccessful = false
          },
        },
      )
      this.isLoading = false
    },
    validatePhone() {
      return this.hasPhoneError ? 'error-phone-invalid' : ''
    },
    sendGtmEvent(): void {
      const event = {
        event: 'gaEvent',
        eventAction: this.isWorkTime ? 'Llamadme(CMN)' : 'Llamadme(CMB)',
        eventCategory: this.eventCategory,
        eventLabel: this.eventLabel,
        url: this.url,
        trigger: 'submit',
        phone_number: this.phone,
      }
      dataLayerPush(event)
    },
  },
  i18n: {
    messages: {
      es: {
        button: 'Contactar con un Asesor Virtual',
        feedbackMessage: 'Gracias por dejarnos tu teléfono.',
        feedbackMessageBold:
          'En unos instantes uno de nuestros agentes se pondrá en contacto contigo.',
        feedbackMessageError: 'Ups, no hemos podido enviar tus datos',
        feedbackMessageErrorBold:
          'Por favor, inténtalo de nuevo o llámanos gratis al {phone}.',
        phoneLabel:
          'Déjanos tu número y **un asesor virtual te llamará ahora:**',
        phonePlaceholder: 'Número de teléfono',
        legalCheckbox: 'Acepto recibir {privacyPolicy}',
        privacyPolicy: 'comunicaciones comerciales',
      },
      ca: {
        button: 'Contactar amb un Assessor Virtual',
        feedbackMessage: 'Gràcies per deixar-nos el teu telèfon.',
        feedbackMessageBold:
          'En uns instants un dels nostres agents es posarà en contacte amb tu.',
        feedbackMessageError: 'Ups, no hem pogut enviar les teves dades',
        feedbackMessageErrorBold:
          "Si us plau, intenta-ho de nou o truca'ns gratis al {phone}.",
        phoneLabel:
          'Deixa’ns el teu número i **un assessor virtual et trucarà ara mateix:**',
        phonePlaceholder: 'Número de telèfon',
        legalCheckbox: 'Accepto rebre {privacyPolicy}',
        privacyPolicy: 'comunicacions comercials',
      },
      en: {
        button: 'Contact a Virtual Advisor',
        feedbackMessage: 'Thank you for leaving your phone.',
        feedbackMessageBold: 'One of our agents will contact you soon.',
        feedbackMessageError: "Oops, we couldn't send your details",
        feedbackMessageErrorBold:
          'Please try again or call us for free at {phone}.',
        phoneLabel:
          'Leave us your number and **a virtual advisor will call you now:**',
        phonePlaceholder: 'Phone number',
        legalCheckbox: 'I agree to receive {privacyPolicy}',
        privacyPolicy: 'commercial information',
      },
    },
  },
}
</script>

<style scoped src="./KaCallModule.css"></style>
