<template>
  <div class="bg-white p-8 rounded-lg shadow-md text-center w-full max-w-md mx-4">
    <h2 class="text-2xl font-bold text-gray-800">Check-in do Evento</h2>
    <p class="text-gray-600 mt-2">Preencha seus dados para confirmar a presença.</p>

    <form @submit.prevent="handleCheckin" class="flex flex-col gap-4 mt-6">
      <input
        v-model="name"
        type="text"
        placeholder="Nome Completo"
        :disabled="isLoading"
        required
        class="px-4 py-3 border border-gray-300 rounded-md w-full focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100"
      />
      <input
        v-model="email"
        type="email"
        placeholder="Seu melhor e-mail"
        :disabled="isLoading"
        required
        class="px-4 py-3 border border-gray-300 rounded-md w-full focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100"
      />
      <input
        v-model="eventCode"
        type="text"
        placeholder="Código do Evento"
        :disabled="isLoading"
        required
        class="px-4 py-3 border border-gray-300 rounded-md w-full focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100"
      />
      <button 
        type="submit" 
        :disabled="isLoading" 
        class="px-4 py-3 bg-blue-600 text-white font-semibold rounded-md cursor-pointer hover:bg-blue-700 transition-colors duration-200 disabled:bg-gray-400 disabled:cursor-not-allowed"
      >
        {{ isLoading ? 'Confirmando...' : 'Confirmar Presença' }}
      </button>
    </form>
    
    <p v-if="statusMessage" class="mt-4 font-semibold text-gray-700">{{ statusMessage }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';

definePageMeta({
  layout: 'checkin',
});

const name = ref('');
const email = ref('');
const eventCode = ref('');
const statusMessage = ref('');
const isLoading = ref(false);

async function handleCheckin() {
  if (!name.value || !email.value || !eventCode.value) {
    statusMessage.value = 'Por favor, preencha todos os campos.';
    return;
  }

  isLoading.value = true;
  statusMessage.value = '';

  try {
    const { data, error } = await useFetch('/api/perform-checkin', {
      method: 'POST',
      body: { 
        name: name.value,
        email: email.value, 
        eventCode: eventCode.value 
      },
    });

    if (error.value) {
      throw error.value;
    }

    statusMessage.value = `Check-in realizado com sucesso, ${data.value.name}!`;
    name.value = '';
    email.value = '';
    eventCode.value = '';
  } catch (err) {
    statusMessage.value = 'Erro ao realizar o check-in. Verifique os dados e tente novamente.';
    console.error(err);
  } finally {
    isLoading.value = false;
  }
}
</script>