<template>
  <div>
    <div id="anchor" />

    <v-form
      v-if="!contactRequestSent"
      ref="form"
      validate-on="submit lazy"
      @submit.prevent="submit"
    >
      <v-container>
        <v-row>
          <v-col cols="12" md="6">
            <v-text-field
              v-model="email"
              :rules="[validateEmail]"
              :label="$t('contact_email')"
              required
              type="email"
            />
          </v-col>

          <v-col cols="12" md="6">
            <v-text-field
              v-model="name"
              :label="$t('contact_name')"
              required
            />
          </v-col>
        </v-row>

        <v-row>
          <v-col cols="12">
            <v-textarea
              v-model="message"
              :rules="[validateNonEmptyMessage]"
              :label="$t('contact_message')"
              required
              maxlength="400"
            />
          </v-col>
        </v-row>

        <!-- Submit Button -->
        <div class="d-flex flex-row justify-center">
          <v-btn
            type="submit"
            variant="outlined"
            :height="54"
            :width="180"
            class="submit-btn"
          >
            {{ $t('contact_submit') }}
          </v-btn>
        </div>

        <div v-if="errorMsg" class="error">
          {{ errorMsg }}
        </div>
      </v-container>
    </v-form>

    <div v-else class="confirmation-message d-flex flex-row justify-center">
      <v-card>
        <v-icon icon="fas fa-check mr-1" />
        {{ $t('contact_confirmation') }}
      </v-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Ref } from '@vue/reactivity'

const router = useRouter()

const form: Ref<HTMLElement | null> = ref(null)

const contactRequestSent: Ref<boolean> = ref(false)

const errorMsg: Ref<string | null> = ref(null)

const email: Ref<string | null> = ref(null)
const name: Ref<string | null> = ref(null)
const message: Ref<string | null> = ref(null)

const validateEmail = (email: string | null) =>
  (!!email && /.+@.+\..+/.test(email)) || "L'adresse e-mail doit être valide"

const validateNonEmptyMessage = (message: string | null) =>
  (!!message && message.length > 0) || 'Le message ne peut pas être vide'

/**
 * Submits the contact form.
 *
 * This function validates the form and sets the value of a variable to indicate whether the form submission was successful.
 *
 * @function
 *
 * @returns {void}
 */
const submit = async (): Promise<void> => {
  const { valid } = await form.value!.validate()

  if (!valid) {
    contactRequestSent.value = false
    return
  }

  const url = 'https://api.ogene.fr/api/contact';
  const headers = {
    'Content-Type': 'application/ld+json'
  };
  const body = {
    "email": email.value,
    "name": name.value,
    "message": message.value
  };

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(body)
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    await response.json();
  } catch (error) {
    console.error('There was a problem with the fetch operation: ', error);
  }

  contactRequestSent.value = true
  errorMsg.value = null

  // Défile vers le début de page pour afficher le message de confirmation
  setTimeout(() => router.push({ path: '', hash: '#anchor' }), 30)
}

</script>

<style scoped lang="scss">
.confirmation-message .v-card {
  padding: 14px;
}
</style>