<template>
  <section class="w-full max-w-4xl mx-auto text-center">
    <h1 class="text-orange-700 text-3xl md:text-4xl font-bold mb-8">
      Buku Tamu
    </h1>

    <!-- Form -->
    <div class="bg-yellow-300/60 rounded-3xl p-6 shadow-xl mb-8">
      <form @submit.prevent="submitMessage" class="space-y-4">
        <input v-model="form.name" type="text" placeholder="Nama"
          class="w-full px-4 py-2 rounded-xl border-2 border-orange-400 focus:ring-2 focus:ring-orange-500">
        <textarea v-model="form.message" placeholder="Ucapan"
          class="w-full px-4 py-2 rounded-xl border-2 border-orange-400 focus:ring-2 focus:ring-orange-500"></textarea>
        <select v-model="form.attendance"
          class="w-full px-4 py-2 rounded-xl border-2 border-orange-400 focus:ring-2 focus:ring-orange-500">
          <option value="hadir">Hadir</option>
          <option value="tidak_hadir">Tidak Hadir</option>
          <option value="mungkin">Mungkin</option>
        </select>
        <button type="submit"
          class="bg-orange-600 hover:bg-orange-700 text-white px-6 py-3 rounded-xl font-semibold shadow-lg">
          Kirim
        </button>
      </form>
    </div>

    <!-- Messages -->
    <div class="space-y-4">
      <div v-for="msg in messages" :key="msg.id" class="bg-white rounded-xl shadow-md p-4 text-left">
        <div class="flex items-center justify-between mb-2">
          <span class="font-bold text-orange-800">{{ msg.nama }}</span>
          <span :class="getAttendanceClass(msg.status_kehadiran)" class="text-sm px-2 py-1 rounded-lg">
            {{ formatAttendance(msg.status_kehadiran) }}
          </span>
        </div>
        <p class="text-gray-700">{{ msg.pesan }}</p>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRuntimeConfig } from '#app';

const route = useRoute();
const config = useRuntimeConfig();
const backendUrl = config.public.apiBaseUrl;
const invitationCode = route.params.code || '';
const guest = route.query.code

const props = defineProps({
  messages: {
    type: Array,
    required: false,
    default: () => []
  }
})

const messages = ref([...props.messages]) // duplikat supaya bisa diubah


const form = ref({ name: '', message: '', attendance: 'hadir' });

// Fungsi untuk mengirim data RSVP ke backend
const submitMessage = async () => {
  if (!form.value.name || !form.value.message) {
    alert('Nama dan ucapan harus diisi!');
    return;
  }


  const payload = {
    nama: form.value.name,
    pesan: form.value.message,
    status_kehadiran: form.value.attendance,
  }

  try {
    console.log('POST to:', `${backendUrl}/api/rsvp/${invitationCode}`, payload)
    const response = await fetch(`${backendUrl}/api/rsvp/${invitationCode}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        nama: form.value.name,
        pesan: form.value.message,
        status_kehadiran: form.value.attendance, 
      }),
      
    });

    if (!response.ok) { 
      console.log(response)
      throw new Error(`Gagal menyimpan RSVP,${response.errors}`);
    }
  
    const result = await response.json();
    messages.value.push(result.data); // Tambahkan RSVP baru ke daftar
    form.value = { name: '', message: '', attendance: 'hadir' };
    alert(result.message); // Tampilkan pesan sukses dari backend
  } catch (error) {
    console.error('Error menyimpan RSVP:', error);
    alert('Terjadi kesalahan saat menyimpan RSVP.');
  }
};

// Fungsi untuk mengatur kelas CSS berdasarkan status kehadiran
const getAttendanceClass = (attendance) => {
  switch (attendance) {
    case 'iya':
      return 'bg-green-100 text-green-700';
    case 'tidak':
      return 'bg-red-100 text-red-700';
    case 'mungkin':
      return 'bg-yellow-100 text-yellow-700';
    default:
      return 'bg-gray-100 text-gray-700';
  }
};

// Fungsi untuk memformat teks kehadiran
const formatAttendance = (attendance) => {
  switch (attendance) {
    case 'iya':
      return 'Hadir';
    case 'tidak':
      return 'Tidak Hadir';
    case 'mungkin':
      return 'Mungkin';
    default:
      return attendance;
  }
};
</script>