<template>
  <div class="p-6 text-center max-w-2xl mx-auto relative">
    <h2 class="text-4xl font-bold bg-gradient-to-r from-orange-600 to-yellow-600 bg-clip-text text-transparent mb-8">
      💌 Guest Book 💌
    </h2>

    <!-- 🎈 Balon Kiri -->
    <img
      src="/balloon2.png"
      alt="Balloons Left"
      class="absolute w-32 md:w-40 -top-12 -left-7.5 animate-swing-top pointer-events-none select-none"
    />

    <!-- 🎈 Balon Kanan -->
    <img
      src="/balloon2.png"
      alt="Balloons Right"
      class="absolute w-32 md:w-40 -top-12 -right-10.5 animate-swing-top pointer-events-none select-none"
    />

    <!-- 💌 Form RSVP -->
    <div
      class="bg-white/80 backdrop-blur-lg rounded-2xl p-8 shadow-xl border border-yellow-100 mb-8 relative z-10"
    >
      <form @submit.prevent="submitMessage" class="space-y-4">
        <!-- Nama Tamu -->
        <div>
          <input
            v-model="form.name"
            type="text"
            :placeholder="guest || 'Nama Lengkap Tamu'"
            class="w-full p-4 border-2 border-yellow-300 rounded-2xl focus:ring-2 focus:ring-orange-400 focus:border-orange-400 transition-all duration-300"
            :disabled="!!guest"
          />
        </div>

        <!-- Pesan/Ucapan -->
        <div>
          <textarea
            v-model="form.message"
            rows="4"
            placeholder="Tulis ucapan dan harapan terbaik..."
            class="w-full p-4 border-2 border-yellow-300 rounded-2xl focus:ring-2 focus:ring-orange-400 focus:border-orange-400 transition-all duration-300 resize-none"
          ></textarea>
        </div>

        <!-- Status Kehadiran -->
        <div>
          <select
            v-model="form.attendance"
            class="w-full p-4 border-2 border-yellow-300 rounded-2xl focus:ring-2 focus:ring-orange-400 focus:border-orange-400 transition-all duration-300 appearance-none bg-white"
          >
            <option value="hadir">✅ Saya Hadir</option>
            <option value="tidak_hadir">❌ Tidak Hadir</option>
            <option value="mungkin">🤔 Mungkin Hadir</option>
          </select>
        </div>

        <!-- Error Message -->
        <div
          v-if="errorMessage"
          class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-xl"
        >
          {{ errorMessage }}
        </div>

        <!-- Submit Button -->
        <button
          type="submit"
          :disabled="!form.name.trim() || !form.message.trim() || submitLoading"
          class="bg-gradient-to-r from-orange-500 to-yellow-500 hover:from-orange-600 hover:to-yellow-600 text-white px-8 py-4 rounded-full font-semibold shadow-lg transition-all duration-300 transform hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed w-full text-lg"
        >
          ✨ {{ submitLoading ? 'Mengirim...' : 'Kirim RSVP' }}
        </button>
      </form>
    </div>

    <!-- 💬 Daftar Pesan -->
    <div v-if="fetchLoading" class="flex items-center justify-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-t-4 border-orange-500 mr-4"></div>
      <span class="text-2xl font-semibold text-orange-700">Memuat ucapan...</span>
    </div>

    <div v-else class="space-y-4 max-h-96 overflow-y-auto px-2 relative z-10">
     <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>

      <div v-if="messages.length === 0" class="bg-white/60 p-8 rounded-2xl">
        <p class="text-gray-600 text-lg">
          Belum ada ucapan. Jadilah yang pertama mengucapkan!
        </p>
      </div>
    </div>
  </div>
</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]) 


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>
<style scoped>
@keyframes swing-top {
  0% {
    transform: rotate(2deg);
  }
  50% {
    transform: rotate(-2deg);
  }
  100% {
    transform: rotate(2deg);
  }
}

.animate-swing-top {
  animation: swing-top 4s ease-in-out infinite;
  transform-origin: bottom center;
}
</style>