<template>
  <LayoutContainer>
    <v-form
      ref="form"
      v-model="valid"
      lazy-validation
    >
      <v-container>
        <h4>
          Veuillez remplir le formulaire ci-dessous
        </h4>

        <i>Les champs dont le nom est suivi d'une astérisque (*) sont obligatoires</i>

        <h6>
          Vos coordonnées
        </h6>

        <!-- Gender selection -->
        <v-row>
          <v-col cols="12">
            <v-radio-group
              v-model="gender"
              row
              mandatory
              inline
            >
              <v-radio label="Madame" value="Madame" />
              <v-radio label="Monsieur" value="Monsieur" />
            </v-radio-group>
          </v-col>
        </v-row>

        <!-- Name and Surname -->
        <v-row>
          <v-col cols="12" md="6">
            <v-text-field
              v-model="name"
              :rules="[validateName]"
              label="Nom*"
              required
            />
          </v-col>

          <v-col cols="12" md="6">
            <v-text-field
              v-model="surname"
              :rules="[validateSurname]"
              label="Prénom*"
              required
            />
          </v-col>
        </v-row>

        <!-- Postal code and city -->
        <v-row>
          <v-col cols="12" md="6">
            <v-text-field
              v-model="postalCode"
              label="Code postal*"
              :rules="[validatePostalCode]"
            />
          </v-col>

          <v-col cols="12" md="6">
            <v-text-field
              v-model="city"
              label="Ville"
            />
          </v-col>
        </v-row>

        <!-- Email and phone on the same line -->
        <v-row>
          <v-col cols="12" md="6">
            <v-text-field
              v-model="email"
              :rules="[validateEmail]"
              label="Email*"
              required
              type="email"
            />
          </v-col>

          <v-col cols="12" md="6">
            <v-text-field
              v-model="phone"
              :rules="[validatePhone]"
              label="Téléphone*"
              type="tel"
            />
          </v-col>
        </v-row>

        <!-- Structure name  -->
        <v-row>
          <v-col cols="12">
            <v-text-field
              v-model="structureName"
              :rules="[validateStructureName]"
              label="Nom de la structure*"
              required
            />
          </v-col>
        </v-row>

        <h6>
          Votre demande concerne
        </h6>

        <!-- Request type and product concerned  -->
        <v-row>
          <v-col cols="12" md="6">
            <v-select
              v-model="requestType"
              :items="requestTypes"
              label="Votre demande concerne*"
              outlined
              dense
            />
          </v-col>

          <v-col cols="12" md="6">
            <v-text-field
              v-model="concernedProduct"
              label="Le produit concerné"
              outlined
              dense
            />
          </v-col>
        </v-row>

        <h6>
          Votre message
        </h6>

        <!-- Message  -->
        <v-row>
          <v-col cols="12">
            <v-textarea
              v-model="message"
              :rules="[validateMessageLength]"
              label="Votre message*"
              required
              outlined
              dense
              maxlength="400"
            />
          </v-col>
        </v-row>

        <!-- Policy and  checkboxes -->
        <v-checkbox
          v-model="privacyPolicy"
          :rules="[(v) => !!v || 'You must accept the privacy policy']"
          label="J'ai pris connaissance de la politique de confidentialité et j'accepte le traitement de mes données personnelles par Opentalent."
        />

        <v-checkbox
          v-model="newsletterSubscription"
          label="Je souhaite recevoir des communications d'Opentalent par email (promotions, informations logiciel…). Je pourrai me désinscrire à tout moment."
        />

        <!-- TODO: Remplacer par un vrai captcha
        voir:
          - https://nuxt.com/modules/recaptcha
          - https://nuxt.com/modules/turnstile
        -->
        <v-checkbox
          v-model="captchaChecked"
          :rules="[(v) => !!v || 'You must pass the captcha']"
          label="Captcha"
        />

        <!-- Submit Button -->
        <v-row>
          <v-col cols="12">
            <v-btn
              :disabled="!valid"
              @click="submitForm"
            >
              Envoyer
            </v-btn>
          </v-col>
        </v-row>
      </v-container>
    </v-form>

    <div v-if="submissionStatus">
      {{ submissionStatus }}
    </div>

  </LayoutContainer>
</template>

<script setup lang="ts">
import { ComputedRef } from "vue";
import { ContactFormData } from "~/types/interface";

const route = useRoute();
const defaultRequestType = route.query.request;

// --- Constants ---
const requestTypes: Array<string> = [
  "Demande d'information",
  "Demande de devis",
  "Demande de démonstration",
  "Demande d'option supplémentaire",
  "Autre",
];


// --- Refs ---
const name: Ref<string | null> = ref(null);

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

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

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

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

const privacyPolicy: Ref<boolean> = ref(false);

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

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

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

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

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

const newsletterSubscription: Ref<boolean> = ref(false);

const captchaChecked: Ref<boolean> = ref(false);

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


// --- Validation ---
const validateName = (name: string | null) => !!name || "Le nom est obligatoire";

const validateSurname = (surname: string | null) => !!surname || "Le prénom est obligatoire";

const validatePostalCode = (postalCode: string | null) =>
  (!!postalCode && /^\d{5}$/.test(postalCode)) || "Le code postal doit être valide";

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

const validatePhone = (email: string | null) =>
  (!!email && /^((\+|00)33\s?|0)[67]([\s.]?\d{2}){4}$/.test(email)) || "Le numéro de téléphone doit être valide";

const validateStructureName = (structureName: string | null) =>
  !!structureName || "Le nom de la structure est requis";

const validateMessageLength = (message: string | null) =>
  (!!message && message.length <= 400) ||
  "Le message ne doit pas dépasser 400 caractères";

// TODO: revoir la validation, ça devrait être géré directement dans le v-form
const valid: ComputedRef<boolean> = computed(() => {
  return (
    validateName(name.value) === true &&
    validateSurname(surname.value) === true &&
    validatePostalCode(postalCode.value) === true &&
    validateEmail(email.value) === true &&
    validatePhone(phone.value) === true &&
    validateStructureName(structureName.value) === true &&
    validateMessageLength(message.value) === true &&
    privacyPolicy.value === true &&
    captchaChecked.value === true
  );
});

// --- Form data (voir si utile) ---
const formData: ContactFormData = reactive({
  gender: null,
  postalCode: null,
  city: "",
  phone: null,
  requestType: null,
  concernedProduct: "",
  newsletterSubscription,
});

const formRefs = {
  ...toRefs(formData),
  name,
  surname,
  email,
  structureName,
  message,
  privacyPolicy,
  valid,
};

// --- Methods ---
const submitForm = () => {
  if (valid.value) {
    // Logique d'envoi du formulaire
    // TODO: implémenter
    submissionStatus.value = "Mail envoyé à contact@opentalent.fr";
  } else {
    console.log("Validation failed!");
    submissionStatus.value = "";
  }
};

const requestType: Ref<string | null> = ref(
  defaultRequestType === "demo" ? "Demande de démonstration" : null
);
</script>

<style scoped lang="scss">
.v-form {
  max-width: 1400px;
  margin: 0 auto;

  h4 {
    font-size: 40px;
    line-height: 95px;
    margin-bottom: 1rem;
  }

  h6 {
    margin-top: 32px;
    font-size: 20px;
    margin-bottom: 1rem;
  }
}
</style>
