<template>
  <div class="w-full min-h-screen bg-gray-100">
    <!-- Loading State -->
    <div v-if="isLoading" class="flex items-center justify-center min-h-screen">
      <div class="text-center">
        <div class="animate-spin rounded-full h-12 w-12 border-t-4 border-blue-500 mx-auto"></div>
        <p class="mt-4 text-gray-600">Loading invitation...</p>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="hasError" class="flex items-center justify-center min-h-screen p-4">
      <div class="max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center">
        <svg class="w-12 h-12 mx-auto text-red-500 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"
          xmlns="http://www.w3.org/2000/svg">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
            d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z">
          </path>
        </svg>
        <p class="text-lg font-semibold text-gray-800 mb-2">Undangan Tidak Ditemukan</p>
        <p class="text-gray-600 mb-6">{{ errorMessage }}</p>
        <NuxtLink to="/"
          class="inline-block bg-blue-500 text-white px-6 py-2 rounded-lg hover:bg-blue-600 transition-colors">
          Kembali ke Beranda
        </NuxtLink>
      </div>
    </div>

    <!-- Data Loaded Successfully -->
    <div v-else-if="pelangganData">
      <!-- Dynamic Component for Known Slugs -->
      <component v-if="dynamicComponent" :is="dynamicComponent" :data="pelangganData" :tamu="tamuData" />

      <!-- Fallback for Unknown Slugs -->
      <div v-else class="container mx-auto p-4">
        <div class="max-w-4xl mx-auto bg-white rounded-lg shadow-lg p-8">
          <h1 class="text-2xl font-bold text-gray-800 mb-1">Invitation Data</h1>
          <div class="text-sm mb-4 text-gray-500">Tampilan ini muncul saat komponen template belum tersedia</div>
          
          <!-- Guest Info -->
          <div class="mb-6 p-4 bg-blue-50 rounded-lg">
            <h2 class="text-lg font-semibold text-gray-700 mb-2">Informasi Tamu</h2>
            <p class="text-gray-600"><strong>Nama:</strong> {{ tamuData.nama_tamu }}</p>
            <p class="text-gray-600"><strong>Kode:</strong> {{ tamuData.kode_invitasi }}</p>
          </div>

          <!-- Customer Info -->
          <div class="mb-6">
            <h2 class="text-lg font-semibold text-gray-700 mb-2">Informasi Pelanggan</h2>
            <p class="text-gray-600"><strong>Nama:</strong> {{ pelangganData.nama_pemesan }}</p>
            <p class="text-gray-600"><strong>Email:</strong> {{ pelangganData.email }}</p>
            <p class="text-gray-600"><strong>No. Telp:</strong> {{ pelangganData.no_tlpn }}</p>
            <p class="text-gray-600"><strong>Status:</strong> {{ pelangganData.status }}</p>
          </div>

          <!-- Template Info -->
          <div class="mb-6">
            <h2 class="text-lg font-semibold text-gray-700 mb-2">Template</h2>
            <p class="text-gray-600"><strong>Nama:</strong> {{ pelangganData.template.nama_template }}</p>
            <p class="text-gray-600"><strong>Slug:</strong> {{ pelangganData.template.slug }}</p>
            <p class="text-gray-600"><strong>Paket:</strong> {{ pelangganData.template.paket }}</p>
          </div>

          <!-- Form Data -->
          <div class="mb-6">
            <h2 class="text-lg font-semibold text-gray-700 mb-2">Data Form</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div v-for="(value, key) in pelangganData.form" :key="key" class="p-3 bg-gray-50 rounded">
                <p class="text-sm font-medium text-gray-700 capitalize">{{ key.replace(/_/g, ' ') }}</p>
                <p v-if="typeof value !== 'object'" class="text-sm text-gray-600 break-words">{{ value || '-' }}</p>
                <pre v-else class="text-xs text-gray-600 overflow-x-auto">{{ JSON.stringify(value, null, 2) }}</pre>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

const route = useRoute()
const config = useRuntimeConfig()
const backendUrl = config.public.apiBaseUrl

// State management
const isLoading = ref(true)
const hasError = ref(false)
const errorMessage = ref('Maaf, undangan yang Anda cari tidak tersedia atau sudah tidak berlaku.')
const invitationData = ref(null)

// Component map
const componentMap = {
  'undangan-minimalis': defineAsyncComponent(() => import('~/components/undangan/undangan-minimalis.vue')),
  'undangan-ulang-tahun-premium': defineAsyncComponent(() => import('~/components/undangan/undangan-ulang-tahun-premium.vue')),
  'undangan-pernikahan-premium': defineAsyncComponent(() => import('~/components/undangan/undangan-pernikahan-premium.vue')),
  'undangan-khitan-premium': defineAsyncComponent(() => import('~/components/undangan/undangan-khitan-premium.vue')),
  'undangan-ulang-tahun-basic': defineAsyncComponent(() => import('~/components/undangan/undangan-ulang-tahun-basic.vue')),
  'undangan-ulang-tahun-starter': defineAsyncComponent(() => import('~/components/undangan/undangan-ulang-tahun-starter.vue')),
  'undangan-khitan-basic': defineAsyncComponent(() => import('~/components/undangan/undangan-khitan-basic.vue')),
  'undangan-khitan-starter': defineAsyncComponent(() => import('~/components/undangan/undangan-khitan-starter.vue'))
}

// Computed properties
const pelangganData = computed(() => invitationData.value?.pelanggan || null)

const tamuData = computed(() => {
  if (!invitationData.value) return null
  return {
    id: invitationData.value.id,
    nama_tamu: invitationData.value.nama_tamu,
    kode_invitasi: invitationData.value.kode_invitasi,
    created_at: invitationData.value.created_at,
    updated_at: invitationData.value.updated_at
  }
})

const dynamicComponent = computed(() => {
  if (!pelangganData.value?.template?.slug) return null
  return componentMap[pelangganData.value.template.slug] || null
})

// Fetch data function
const fetchInvitation = async () => {
  try {
    console.log('🔍 Fetching invitation for code:', route.params.code)
    
    const response = await $fetch(`${backendUrl}/api/pelanggans/code/${route.params.code}`)
    
    console.log('✅ API response:', response)

    // Validate response
    if (!response.success) {
      throw new Error(response.message || 'Undangan tidak ditemukan')
    }

    if (!response.data || !response.data.pelanggan) {
      throw new Error('Data undangan tidak valid')
    }

    if (!response.data.pelanggan.template) {
      throw new Error('Template undangan tidak ditemukan')
    }

    // Set data
    invitationData.value = response.data
    
    console.log('📦 Pelanggan:', pelangganData.value)
    console.log('🎫 Tamu:', tamuData.value)
    console.log('📝 Template slug:', pelangganData.value?.template?.slug)
    console.log('🧩 Component:', dynamicComponent.value ? 'Found' : 'Not found')

  } catch (err) {
    console.error('❌ Error fetching invitation:', err)
    hasError.value = true
    errorMessage.value = err.message || 'Terjadi kesalahan saat memuat undangan.'
  } finally {
    isLoading.value = false
  }
}

// Fetch on client side only
onMounted(() => {
  fetchInvitation()
})

// Set meta tags
useHead(() => ({
  title: pelangganData.value?.nama_pemesan 
    ? `Undangan dari ${pelangganData.value.nama_pemesan}` 
    : 'Undangan Digital',
  meta: [
    {
      name: 'description',
      content: pelangganData.value
        ? `${pelangganData.value.nama_pemesan} mengundang Anda untuk menghadiri acara ${pelangganData.value.template?.nama_template || 'spesial'}!`
        : 'Undangan Digital'
    },
  ],
}))
</script>

<style scoped>
pre {
  text-align: left;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>