<template>
  <div>
    <div class="backdrop" @click="closeCallModule" />
    <div class="opened-call-module">
      <div class="top-section">
        <ma-button
          class="close-button"
          category="tertiary"
          @click="closeCallModule"
          icon="Close"
        />
        <ka-form v-if="!isSuccessful" @submit="callMe">
          <ma-stack space="medium">
            <ma-heading
              tone="gray-dark"
              size="xsmall"
              v-t="'solveDoubts'"
              class="title"
            />
            <ma-stack space="xsmall">
              <ka-form-field
                :label="`${$t('phoneLabel')}`"
                :placeholder="`${$t('phonePlaceholder')}`"
                is-required
                hide-asterisk
                :validators="[validators.checkPhoneNumber]"
                v-model="phone"
              />
              <ka-legal-checkbox
                v-model="hasAcceptedLegal"
                hide-asterisk
                size="xsmall"
              />
            </ma-stack>
            <ma-stack space="xsmall">
              <ma-button
                v-if="isWorkTime"
                type="submit"
                icon="Phone"
                :text="$t('button')"
              />
              <ma-button
                v-else
                category="primary"
                type="submit"
                :loading="isLoading"
                :text="$t('button')"
              />
              <ma-text
                class="text"
                size="small"
                v-markdown="$t('disclaimerCall')"
              />
            </ma-stack>
            <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-else space="small">
          <ma-heading
            tone="gray-dark"
            size="xsmall"
            v-t="'solveDoubts'"
            class="title"
          />
          <ma-stack space="small" class="feedback">
            <ma-text size="small" v-t="'feedbackMessage'" />
            <ma-text bold v-t="'feedbackMessageBold'" />
          </ma-stack>
        </ma-stack>
      </div>
      <div :class="isWorkTime ? 'bottom-section' : ''">
        <ma-text v-if="isSuccessful" class="text" size="small">
          <span v-markdown="$t('disclaimerCall')" />
        </ma-text>
        <ma-text v-if="!isSuccessful && isWorkTime" class="text" size="small">
          <span v-markdown="$t('callUsFooter')" />
        </ma-text>
        <a
          v-if="!isSuccessful && isWorkTime"
          class="link gtm_c2c-flotante"
          :href="`tel:${businessUnit.phone}`"
        >
          <ma-text bold size="small" tone="pink">
            {{ businessUnit.phone }}
          </ma-text>
        </a>
      </div>
    </div>
  </div>
</template>

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

const closeModuleAfterOkMs = 8000

export default {
  components: { KaForm, KaFormField, KaLegalCheckbox },
  props: {
    businessUnitName: {
      type: String as PropType<BusinessUnitType>,
      default: 'default',
    },
    eventCategory: { type: String, required: true },
    eventLabel: { type: String, required: true },
    isWorkTime: { type: Boolean, required: true },
  },
  data() {
    return {
      phone: '',
      hasAcceptedLegal: false,
      isSuccessful: false,
      isLoading: false,
      hasFeedbackError: false,
    }
  },
  computed: {
    businessUnit(): BusinessUnit {
      return businessUnits[this.businessUnitName] as BusinessUnit
    },
    validators() {
      return validators
    },
  },
  methods: {
    async callMe() {
      this.hasFeedbackError = false
      await this.createLead()
    },
    async createLead(): Promise<void> {
      this.isLoading = true
      await handleCreatePhoneLead().execute(
        {
          phone: this.phone,
          url: location.href,
          isCallMeBack: !this.isWorkTime,
          businessUnit: this.businessUnitName,
        },
        {
          respondWithSuccess: () => {
            this.sendGtmEvent()
            this.isSuccessful = true
          },
          respondWithError: () => {
            this.hasFeedbackError = true
            this.isSuccessful = false
          },
        },
      )
      this.isLoading = false
      setTimeout(() => this.closeCallModule(), closeModuleAfterOkMs)
    },
    sendGtmEvent(): void {
      const event = {
        event: 'gaEvent',
        eventAction: this.isWorkTime ? 'Llamadme(CMN)' : 'Llamadme(CMB)',
        eventCategory: this.eventCategory,
        eventLabel: this.eventLabel,
        phone_number: `+34${this.phone}`,
        url: location.href,
        trigger: 'submit',
      }
      dataLayerPush(event)
    },
    closeCallModule(): void {
      dataLayerPush({
        event: 'gaEvent',
        eventAction: 'Flotante',
        eventCategory: this.eventCategory,
        eventLabel: 'Cerrar flotante',
      })
      dataLayerPush({ event: 'popup_close', method: 'cmn' })
      this.$emit('close')
    },
  },
  i18n: {
    messages: {
      es: {
        solveDoubts: 'Resolvemos tus dudas en 5 minutos',
        disclaimerCall: 'Recuerda, te llamaremos desde un número **93**',
        closeAria: 'Cerrar módulo',
        button: 'Contactar con un Asesor Virtual',
        callUsFooter: 'Si prefieres, **llámanos**. Es gratis',
        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 de teléfono',
        phonePlaceholder: 'Número de teléfono',
        legalCheckbox: 'Acepto recibir {privacyPolicy}',
        privacyPolicy: 'comunicaciones comerciales',
      },
      ca: {
        solveDoubts: 'Resolem els teus dubtes en 5 minuts',
        disclaimerCall: "Recorda, et trucarem des d'un número **93**",
        closeAria: 'Tancar mòdul',
        button: 'Contactar amb un Assessor Virtual',
        callUsFooter: "Si prefereixes, **truca'ns**. És gratis",
        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 el teu número de telèfon',
        phonePlaceholder: 'Número de telèfon',
        legalCheckbox: 'Accepto rebre {privacyPolicy}',
        privacyPolicy: 'comunicacions comercials',
      },
      en: {
        solveDoubts: 'We solve your doubts in 5 minutes',
        disclaimerCall: 'Remember that we will call you from a **93**',
        closeAria: 'Close module',
        button: 'Contact a virtual advisor',
        callUsFooter: "If you prefer, **call us**. It's free",
        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 phone number',
        phonePlaceholder: 'Phone number',
        legalCheckbox: 'I agree to receive {privacyPolicy}',
        privacyPolicy: 'commercial information',
      },
    },
  },
}
</script>

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