<template>
  <div class="min-h-screen bg-gray-100 flex items-center justify-center p-4">
    <div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-5xl">
      <h1 class="text-2xl font-bold mb-6 text-center text-gray-800">
        Manajemen Daftar Tamu & RSVP
      </h1>

      <!-- Input Kode Pelanggan -->
      <div class="mb-6">
        <form @submit.prevent="handleFetchGuests" class="flex gap-2">
          <input
            v-model="kodePelanggan"
            type="text"
            placeholder="Kode Pelanggan (contoh: PLG-123456)"
            class="flex-1 border border-gray-300 p-3 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
          />
          <button
            type="submit"
            class="bg-blue-500 text-white px-6 py-3 rounded-lg hover:bg-blue-600 transition disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap"
            :disabled="loading"
          >
            {{ loading ? 'Memuat...' : 'Cari' }}
          </button>
        </form>
        <p v-if="errorMessage && !dataLoaded" class="text-red-500 mt-3 text-sm">
          {{ errorMessage }}
        </p>
      </div>

      <!-- Area Data Tamu -->
      <div v-if="dataLoaded">
        <!-- Info Kode Pelanggan -->
        <div class="bg-blue-50 p-3 rounded-lg mb-6">
          <p class="text-sm text-gray-700">
            <span class="font-semibold">Kode Pelanggan:</span>
            {{ kodePelanggan.toUpperCase() }}
          </p>
        </div>

        <!-- Ringkasan RSVP (4 kolom) -->
        <div class="bg-green-50 p-4 rounded-lg mb-6 border border-green-200">
          <h3 class="font-semibold text-green-800 mb-2">Ringkasan RSVP</h3>
          <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div>
              <p class="text-gray-600">Hadir</p>
              <p class="font-bold text-green-600">{{ rsvpSummary.hadir }}</p>
            </div>
            <div>
              <p class="text-gray-600">Tidak Hadir</p>
              <p class="font-bold text-red-600">{{ rsvpSummary.tidak_hadir }}</p>
            </div>
            <div>
              <p class="text-gray-600">Mungkin</p>
              <p class="font-bold text-yellow-600">{{ rsvpSummary.mungkin }}</p>
            </div>
            <div>
              <p class="text-gray-600">Belum RSVP</p>
              <p class="font-bold text-gray-600">{{ rsvpSummary.belum_rsvp }}</p>
            </div>
          </div>
        </div>

        <!-- Form Tambah Tamu -->
        <form @submit.prevent="handleAddGuest" class="mb-6">
          <label class="block text-sm font-semibold text-gray-700 mb-2">
            Tambah Tamu Baru
          </label>
          <div class="flex gap-2">
            <input
              v-model="namaTamu"
              type="text"
              placeholder="Nama Tamu"
              class="flex-1 border border-gray-300 p-3 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500"
              required
            />
            <button
              type="submit"
              class="bg-green-500 text-white px-6 py-3 rounded-lg hover:bg-green-600 transition disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap"
              :disabled="loading"
            >
              {{ loading ? 'Menambahkan...' : 'Tambah' }}
            </button>
          </div>
        </form>

        <p v-if="errorMessage && dataLoaded" class="text-red-500 mb-4 text-sm">
          {{ errorMessage }}
        </p>
        <p v-if="successMessage" class="text-green-500 mb-4 text-sm">
          {{ successMessage }}
        </p>

        <!-- Tabel Daftar Tamu -->
        <div class="mt-6">
          <h2 class="text-lg font-semibold text-gray-800 mb-3">
            Daftar Tamu ({{ guests.length }})
          </h2>

          <div v-if="guests.length > 0" class="overflow-x-auto rounded-lg border border-gray-200 mb-10">
            <table class="w-full">
              <thead>
                <tr class="bg-gray-100 border-b border-gray-200">
                  <th class="p-3 text-left font-semibold text-gray-700">No</th>
                  <th class="p-3 text-left font-semibold text-gray-700">Nama Tamu</th>
                  <th class="p-3 text-left font-semibold text-gray-700">Kode Invitasi</th>
                  <th class="p-3 text-left font-semibold text-gray-700">Status RSVP</th>
                  <th class="p-3 text-center font-semibold text-gray-700">Aksi</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="(guest, index) in guests"
                  :key="guest.id"
                  class="border-b border-gray-100 hover:bg-gray-50 transition"
                >
                  <td class="p-3 text-gray-700">{{ index + 1 }}</td>
                  <td class="p-3 text-gray-800 font-medium">{{ guest.nama_tamu }}</td>
                  <td class="p-3">
                    <div class="flex items-center gap-2">
                      <a
                        :href="`${config.public.baseUrl}/p/${guest.kode_invitasi}`"
                        target="_blank"
                        class="text-gray-600 font-mono text-sm hover:text-blue-600 hover:underline transition"
                        @click.stop
                      >
                        {{ guest.kode_invitasi }}
                      </a>
                      <button
                        @click="shareInvitationLink(guest.kode_invitasi)"
                        class="bg-indigo-500 hover:bg-indigo-600 text-white px-3 py-1 rounded-lg text-xs font-medium transition shadow-sm whitespace-nowrap flex items-center gap-1"
                        :disabled="loading"
                        title="Bagikan Link"
                      >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.367 2.684 3 3 0 00-5.367-2.684z"/>
                        </svg>
                        Share
                      </button>
                    </div>
                  </td>
                  <td class="p-3">
                    <span
                      v-if="guest.rsvp"
                      :class="{
                        'px-3 py-1 rounded-full text-xs font-medium': true,
                        'bg-green-100 text-green-800': guest.rsvp.status_kehadiran === 'hadir',
                        'bg-red-100 text-red-800': guest.rsvp.status_kehadiran === 'tidak_hadir',
                        'bg-yellow-100 text-yellow-800': guest.rsvp.status_kehadiran === 'mungkin'
                      }"
                    >
                      {{ guest.rsvp.status_kehadiran === 'hadir' ? 'Hadir' :
                         guest.rsvp.status_kehadiran === 'tidak_hadir' ? 'Tidak Hadir' : 'Mungkin' }}
                    </span>
                    <span v-else class="text-gray-400 text-xs italic">Belum RSVP</span>
                  </td>
                  <td class="p-3 text-center">
                    <button
                      @click="handleDeleteGuest(guest.id)"
                      class="bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition disabled:bg-gray-400 disabled:cursor-not-allowed text-sm"
                      :disabled="loading"
                    >
                      Hapus
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- Daftar RSVP Lengkap -->
        <div class="mt-10">
          <h2 class="text-lg font-semibold text-gray-800 mb-3">
            Daftar RSVP ({{ allRsvps.length }})
          </h2>

          <div v-if="allRsvps.length > 0" class="overflow-x-auto rounded-lg border border-gray-200">
            <table class="w-full text-sm">
              <thead>
                <tr class="bg-indigo-50 border-b border-indigo-200">
                  <th class="p-3 text-left font-semibold text-indigo-700">No</th>
                  <th class="p-3 text-left font-semibold text-indigo-700">Nama (RSVP)</th>
                  <th class="p-3 text-left font-semibold text-indigo-700">Nama Tamu (Undangan)</th>
                  <th class="p-3 text-left font-semibold text-indigo-700">Kode</th>
                  <th class="p-3 text-left font-semibold text-indigo-700">Status</th>
                  <th class="p-3 text-left font-semibold text-indigo-700">Ucapan</th>
                  <th class="p-3 text-left font-semibold text-indigo-700">Waktu</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="(rsvp, index) in allRsvps"
                  :key="rsvp.id"
                  class="border-b border-gray-100 hover:bg-indigo-50 transition"
                >
                  <td class="p-3 text-gray-700">{{ index + 1 }}</td>
                  <td class="p-3 font-medium text-gray-800">{{ rsvp.nama || '-' }}</td>
                  <td class="p-3 text-gray-600 italic">{{ rsvp.nama_tamu || '-' }}</td>
                  <td class="p-3">
                    <code class="text-xs bg-gray-100 px-2 py-1 rounded">{{ rsvp.kode_invitasi }}</code>
                  </td>
                  <td class="p-3">
                    <span
                      :class="{
                        'px-2 py-1 rounded-full text-xs font-medium': true,
                        'bg-green-100 text-green-800': rsvp.status_kehadiran === 'hadir',
                        'bg-red-100 text-red-800': rsvp.status_kehadiran === 'tidak_hadir',
                        'bg-yellow-100 text-yellow-800': rsvp.status_kehadiran === 'mungkin'
                      }"
                    >
                      {{ rsvp.status_kehadiran === 'hadir' ? 'Hadir' :
                         rsvp.status_kehadiran === 'tidak_hadir' ? 'Tidak Hadir' : 'Mungkin' }}
                    </span>
                  </td>
                  <td class="p-3 text-gray-600 max-w-xs truncate" :title="rsvp.pesan">
                    {{ rsvp.pesan || '-' }}
                  </td>
                  <td class="p-3 text-xs text-gray-500">
                    {{ formatDate(rsvp.created_at) }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div v-else class="text-center py-8 bg-indigo-50 rounded-lg border border-indigo-200">
            <p class="text-indigo-600 font-medium">Belum ada RSVP dari tamu.</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// ---------- STATE ----------
const kodePelanggan = ref('');
const dataLoaded = ref(false);
const guests = ref([]);
const namaTamu = ref('');
const errorMessage = ref('');
const successMessage = ref('');
const loading = ref(false);
const rsvpSummary = ref({ hadir: 0, tidak_hadir: 0, mungkin: 0, belum_rsvp: 0 });
const allRsvps = ref([]);

const config = useRuntimeConfig();
const backendUrl = config.public.apiBaseUrl;

// ---------- UTILS ----------
const formatDate = (dateString) => {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleString('id-ID', {
    day: '2-digit', month: 'short', year: 'numeric',
    hour: '2-digit', minute: '2-digit'
  });
};

const shareInvitationLink = async (kodeInvitasi) => {
  const url = `${config.public.baseUrl}/p/${kodeInvitasi}`;
  if (navigator.share) {
    try { await navigator.share({ title: 'Undangan', url }); }
    catch (e) { if (e.name !== 'AbortError') copyToClipboard(url); }
  } else copyToClipboard(url);
};

const copyToClipboard = (text) => {
  navigator.clipboard.writeText(text).then(() => {
    const old = successMessage.value;
    successMessage.value = 'Link disalin!';
    setTimeout(() => successMessage.value = old, 2000);
  });
};

// ---------- FETCH RSVP PER KODE ----------
const fetchRsvpForGuest = async (kodeInvitasi) => {
  try {
    const res = await $fetch(`${backendUrl}/api/rsvp/${kodeInvitasi}`, { method: 'GET' });
    return res.success && res.data?.length ? res.data[0] : null;
  } catch (e) {
    console.error('RSVP fetch error:', e);
    return null;
  }
};

// ---------- FETCH SEMUA RSVP (hanya yang ada) ----------
const fetchAllRsvps = async () => {
  const list = [];
  for (const g of guests.value) {
    const r = await fetchRsvpForGuest(g.kode_invitasi);
    if (r) {
      r.nama_tamu = g.nama_tamu;          // tambahkan nama tamu
      r.kode_invitasi = g.kode_invitasi;   // tambahkan kode
      list.push(r);
    }
  }
  allRsvps.value = list.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
};

// ---------- FETCH GUESTS + COUNTER ----------
const handleFetchGuests = async () => {
  if (!kodePelanggan.value.trim()) {
    errorMessage.value = 'Kode pelanggan harus diisi.';
    return;
  }

  loading.value = true;
  errorMessage.value = '';
  successMessage.value = '';
  rsvpSummary.value = { hadir: 0, tidak_hadir: 0, mungkin: 0, belum_rsvp: 0 };
  allRsvps.value = [];

  try {
    const res = await $fetch(`${backendUrl}/api/guests/${kodePelanggan.value.toUpperCase()}`, { method: 'GET' });
    if (!res.success) throw new Error(res.message || 'Gagal mengambil data tamu');

    const raw = res.data || [];
    let hadir = 0, tidak_hadir = 0, mungkin = 0;

    const guestsWithRsvp = await Promise.all(
      raw.map(async (g) => {
        const r = await fetchRsvpForGuest(g.kode_invitasi);
        g.rsvp = r;

        if (r?.status_kehadiran) {
          if (r.status_kehadiran === 'hadir') hadir++;
          else if (r.status_kehadiran === 'tidak_hadir') tidak_hadir++;
          else if (r.status_kehadiran === 'mungkin') mungkin++;
        }
        return g;
      })
    );

    const total = raw.length;
    const belum = total - hadir - tidak_hadir - mungkin;

    guests.value = guestsWithRsvp;
    rsvpSummary.value = { hadir, tidak_hadir, mungkin, belum_rsvp: belum };

    await fetchAllRsvps();

    dataLoaded.value = true;
    successMessage.value = 'Data tamu & RSVP berhasil dimuat!';
    setTimeout(() => successMessage.value = '', 3000);
  } catch (e) {
    errorMessage.value = e.message || 'Pelanggan tidak ditemukan.';
    dataLoaded.value = false;
  } finally {
    loading.value = false;
  }
};

// ---------- TAMBAH & HAPUS ----------
const handleAddGuest = async () => {
  if (!namaTamu.value.trim()) { errorMessage.value = 'Nama tamu harus diisi.'; return; }
  loading.value = true;
  try {
    const res = await $fetch(`${backendUrl}/api/guests`, {
      method: 'POST',
      body: { kode_pelanggan: kodePelanggan.value.toUpperCase(), nama_tamu: namaTamu.value.trim() }
    });
    if (res.success) {
      namaTamu.value = '';
      successMessage.value = 'Tamu ditambahkan!';
      setTimeout(() => successMessage.value = '', 2000);
      await handleFetchGuests();
    } else errorMessage.value = res.message || 'Gagal tambah tamu.';
  } catch (e) {
    errorMessage.value = e.data?.message || 'Error saat tambah tamu.';
  } finally { loading.value = false; }
};

const handleDeleteGuest = async (id) => {
  if (!confirm('Hapus tamu ini?')) return;
  loading.value = true;
  try {
    const res = await $fetch(`${backendUrl}/api/guests/${id}`, { method: 'DELETE' });
    if (res.success) {
      successMessage.value = 'Tamu dihapus!';
      setTimeout(() => successMessage.value = '', 2000);
      await handleFetchGuests();
    } else errorMessage.value = res.message || 'Gagal hapus.';
  } catch (e) {
    errorMessage.value = e.data?.message || 'Error hapus tamu.';
  } finally { loading.value = false; }
};
</script>