<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-3xl">
      <h1 class="text-2xl font-bold mb-6 text-center text-gray-800">
        Manajemen Daftar Tamu
      </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 (Muncul setelah fetch berhasil) -->
      <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>
        
        <!-- 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">
            <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-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 Invitasi"
                      >
                        <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"></path>
                        </svg>
                        Share
                      </button>
                    </div>
                  </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 v-else class="text-center py-8 bg-gray-50 rounded-lg border border-gray-200">
            <p class="text-gray-500">Belum ada tamu yang ditambahkan.</p>
            <p class="text-gray-400 text-sm mt-2">Tambahkan tamu pertama menggunakan form di atas.</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// State Management
const kodePelanggan = ref('');
const dataLoaded = ref(false);
const guests = ref([]);
const namaTamu = ref('');
const errorMessage = ref('');
const successMessage = ref('');
const loading = ref(false);
const config = useRuntimeConfig();
const backendUrl = config.public.apiBaseUrl;

// Runtime Config
const { public: { apiBase } } = useRuntimeConfig();

// Share invitation link
const shareInvitationLink = async (kodeInvitasi) => {
  const inviteUrl = `${config.public.baseUrl}/p/${kodeInvitasi}`;
  
  if (navigator.share) {
    // Native Web Share API (mobile)
    try {
      await navigator.share({
        title: 'Undangan Pernikahan',
        text: 'Silakan buka undangan pernikahan saya',
        url: inviteUrl,
      });
    } catch (error) {
      if (error.name !== 'AbortError') {
        copyToClipboard(inviteUrl);
      }
    }
  } else {
    // Fallback to copy to clipboard (desktop)
    copyToClipboard(inviteUrl);
  }
};

// Copy to clipboard function
const copyToClipboard = (text) => {
  navigator.clipboard.writeText(text).then(() => {
    // Show temporary success message
    const originalText = successMessage.value;
    successMessage.value = 'Link undangan berhasil disalin!';
    setTimeout(() => {
      successMessage.value = originalText;
    }, 2000);
  }).catch((err) => {
    console.error('Failed to copy: ', err);
    // Fallback for older browsers
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    try {
      document.execCommand('copy');
      const originalText = successMessage.value;
      successMessage.value = 'Link undangan berhasil disalin!';
      setTimeout(() => {
        successMessage.value = originalText;
      }, 2000);
    } catch (err) {
      console.error('Fallback copy failed: ', err);
    }
    document.body.removeChild(textArea);
  });
};

// Fetch guests data based on customer code
const handleFetchGuests = async () => {
  if (!kodePelanggan.value.trim()) {
    errorMessage.value = 'Kode pelanggan harus diisi.';
    return;
  }

  loading.value = true;
  errorMessage.value = '';
  successMessage.value = '';
  
  try {
    const response = await $fetch(`${backendUrl}/api/guests/${kodePelanggan.value.toUpperCase()}`, {
      method: 'GET',
    });
    
    if (response.success) {
      dataLoaded.value = true;
      guests.value = response.data || [];
      successMessage.value = 'Data tamu berhasil dimuat!';
      setTimeout(() => { successMessage.value = ''; }, 3000);
    } else {
      errorMessage.value = response.message || 'Gagal mengambil daftar tamu.';
      dataLoaded.value = false;
    }
  } catch (error) {
    console.error('Fetch guests error:', error);
    errorMessage.value = error.data?.message || 'Pelanggan tidak ditemukan atau pesanan belum diterima.';
    dataLoaded.value = false;
  } finally {
    loading.value = false;
  }
};

// Add new guest
const handleAddGuest = async () => {
  if (!namaTamu.value.trim()) {
    errorMessage.value = 'Nama tamu harus diisi.';
    return;
  }

  loading.value = true;
  errorMessage.value = '';
  successMessage.value = '';
  
  try {
    const response = await $fetch(`${backendUrl}/api/guests`, {
      baseURL: apiBase,
      method: 'POST',
      body: {
        kode_pelanggan: kodePelanggan.value.toUpperCase(),
        nama_tamu: namaTamu.value.trim(),
      },
    });
    
    if (response.success) {
      guests.value.push(response.data);
      namaTamu.value = '';
      successMessage.value = 'Tamu berhasil ditambahkan!';
      setTimeout(() => { successMessage.value = ''; }, 3000);
    } else {
      errorMessage.value = response.message || 'Gagal menambahkan tamu.';
    }
  } catch (error) {
    console.error('Add guest error:', error);
    if (error.status === 422 && error.data?.errors) {
      errorMessage.value = Object.values(error.data.errors).flat().join(' ');
    } else {
      errorMessage.value = error.data?.message || 'Terjadi kesalahan saat menambahkan tamu.';
    }
  } finally {
    loading.value = false;
  }
};

// Delete guest
const handleDeleteGuest = async (id) => {
  if (!confirm('Apakah Anda yakin ingin menghapus tamu ini?')) {
    return;
  }

  loading.value = true;
  errorMessage.value = '';
  successMessage.value = '';
  
  try {
    const response = await $fetch(`${backendUrl}/api/guests/${id}`, {
      baseURL: apiBase,
      method: 'DELETE',
    });
    
    if (response.success) {
      guests.value = guests.value.filter(guest => guest.id !== id);
      successMessage.value = 'Tamu berhasil dihapus!';
      setTimeout(() => { successMessage.value = ''; }, 3000);
    } else {
      errorMessage.value = response.message || 'Gagal menghapus tamu.';
    }
  } catch (error) {
    console.error('Delete guest error:', error);
    errorMessage.value = error.data?.message || 'Terjadi kesalahan saat menghapus tamu.';
  } finally {
    loading.value = false;
  }
};
</script>