<script setup>
import { motion } from 'motion-v'
import {
  ArrowRight,
  Calendar,
  Car,
  Check,
  CreditCard,
  Download,
  MapPin,
  Shield,
  Star,
} from 'lucide-vue-next'
import { formatPublicDateTime, formatPublicMoney, resolvePublicApiError, resolvePublicAssetUrl } from '~/content/utils'
import { resolvePrivateFlowToken } from '~/utils/private-flow-route'
import { buildRentSearchRoute } from '~/utils/public-routes'

const props = defineProps({
  token: {
    type: String,
    default: '',
  },
})

const { createCheckout, fetchBooking } = usePublicBooking()
const { locale, localizedPath } = usePublicLocale()
const ui = usePublicUi()
const runtimeConfig = useRuntimeConfig()
const route = useRoute()

const isLoading = ref(true)
const isStartingCheckout = ref(false)
const checkoutError = ref('')
const loadError = ref('')
const bookingData = ref(null)

const bookingToken = computed(() => String(props.token || '').trim() || resolvePrivateFlowToken(route, '/track', 'id'))

function formatMoney(amount, currencyCode) {
  return formatPublicMoney(amount, currencyCode || 'USD', locale.value)
}

function formatDateTime(value) {
  return formatPublicDateTime(value, locale.value)
}

const booking = computed(() => bookingData.value?.booking || null)
const documents = computed(() => bookingData.value?.documents || [])
const vehicleImageUrl = computed(() => resolvePublicAssetUrl(
  booking.value?.vehicle?.imageUrl || '',
  runtimeConfig.public.apiBaseUrl,
))
const vehicleName = computed(() => booking.value?.vehicle?.name || '')
const vehicleCategory = computed(() => booking.value?.vehicle?.category || '')
const paymentSummary = computed(() => booking.value?.checkout || null)
const configuredPrepayment = computed(() => paymentSummary.value?.prepayment || null)
const hasConfiguredPrepayment = computed(() => Number(configuredPrepayment.value?.amount || 0) > 0)
const approvalStatus = computed(() => String(paymentSummary.value?.approvalStatus || '').trim())
const latestSession = computed(() => paymentSummary.value?.latestSession || null)
const providerLabel = computed(() => paymentSummary.value?.providerLabel || 'keepz.me')
const paymentMessage = computed(() => paymentSummary.value?.approvalMessage || '')
const paymentCtaLabel = computed(() => paymentSummary.value?.ctaLabel || '')
const hasAmountDue = computed(() => Number(paymentSummary.value?.amountDue || 0) > 0)
const isPaymentAvailable = computed(() => hasConfiguredPrepayment.value && Boolean(paymentSummary.value?.available) && hasAmountDue.value)
const hasReusableCheckoutLink = computed(() => {
  const status = String(latestSession.value?.status || '').toLowerCase()
  return Boolean(latestSession.value?.redirectUrl) && ['created', 'redirect_ready'].includes(status)
})
const isPaymentSettled = computed(() => {
  return String(paymentSummary.value?.mode || '').toLowerCase() === 'settled' || !hasAmountDue.value
})
const isBookingClosed = computed(() => {
  return approvalStatus.value === 'cancelled' || booking.value?.status === 'cancelled'
})

const titleCopy = computed(() => {
  if (booking.value?.status === 'pending') {
    return ui.value.track.reservationReceived
  }

  return ui.value.track.reservationConfirmed
})

const descriptionCopy = computed(() => {
  if (booking.value?.status === 'pending') {
    return vehicleName.value
      ? ui.value.track.pendingDescriptionWithVehicle.replace('{vehicle}', vehicleName.value)
      : ui.value.track.pendingDescription
  }

  return vehicleName.value
    ? ui.value.track.confirmedDescriptionWithVehicle.replace('{vehicle}', vehicleName.value)
    : ui.value.track.confirmedDescription
})

const isAwaitingApproval = computed(() => {
  return approvalStatus.value === 'pending_review'
})

const isApprovalPendingPayment = computed(() => {
  return hasConfiguredPrepayment.value && (isAwaitingApproval.value || String(paymentSummary.value?.mode || '').toLowerCase() === 'approval_pending')
})

const paymentLabel = computed(() => {
  if (!paymentSummary.value) {
    return ui.value.track.bookingTotal
  }

  if (paymentSummary.value.mode === 'prepayment') {
    return ui.value.track.prepaymentDue
  }

  if (paymentSummary.value.mode === 'balance') {
    return ui.value.track.balanceDue
  }

  if (paymentSummary.value.mode === 'settled') {
    return ui.value.track.totalPaid
  }

  if (isApprovalPendingPayment.value) {
    return ui.value.track.prepaymentDue
  }

  return hasAmountDue.value ? ui.value.track.amountDue : ui.value.track.bookingTotal
})

const paymentAmount = computed(() => {
  if (!booking.value?.financials) {
    return 0
  }

  if (paymentSummary.value?.mode === 'settled') {
    return booking.value.financials.totalAmount
  }

  if (paymentSummary.value?.amountDue > 0) {
    return paymentSummary.value.amountDue
  }

  return booking.value.financials.totalAmount
})

const primaryActionLabel = computed(() => {
  if (paymentCtaLabel.value) {
    return paymentCtaLabel.value
  }

  if (isPaymentAvailable.value) {
    return ui.value.track.openPayment
  }

  return ui.value.track.browseFleet
})

const primaryActionIcon = computed(() => {
  return isPaymentAvailable.value ? CreditCard : ArrowRight
})

const primaryActionClasses = computed(() => {
  return isPaymentAvailable.value
    ? 'w-full sm:w-auto px-10 py-5 bg-brand-orange text-white rounded-2xl font-bold text-lg hover:bg-[#E66000] hover:shadow-[0_8px_24px_rgba(249,115,22,0.3)] hover:-translate-y-0.5 transition-all duration-300 flex items-center justify-center gap-3 group disabled:pointer-events-none'
    : 'w-full sm:w-auto px-10 py-5 bg-brand-orange text-white rounded-2xl font-bold text-lg transition-all duration-300 flex items-center justify-center gap-3 group disabled:pointer-events-none'
})

const isPrimaryActionDisabled = computed(() => {
  if (isStartingCheckout.value) {
    return true
  }

  if (!paymentSummary.value) {
    return false
  }

  if (isAwaitingApproval.value || isBookingClosed.value) {
    return true
  }

  if (isPaymentSettled.value) {
    return true
  }

  return !isPaymentAvailable.value
})

const paymentStateTheme = computed(() => {
  if (isBookingClosed.value) {
    return {
      wrapper: 'bg-red-50/70 border-red-100/70 text-red-800',
      eyebrow: 'text-red-600',
    }
  }

  if (isPaymentSettled.value) {
    return {
      wrapper: 'bg-emerald-50/70 border-emerald-100/70 text-emerald-800',
      eyebrow: 'text-emerald-600',
    }
  }

  if (isPaymentAvailable.value) {
    return {
      wrapper: 'bg-emerald-50/70 border-emerald-100/70 text-emerald-800',
      eyebrow: 'text-emerald-600',
    }
  }

  return {
    wrapper: 'bg-amber-50/70 border-amber-100/70 text-amber-800',
    eyebrow: 'text-amber-600',
  }
})

const downloadDocumentUrl = computed(() => {
  return resolvePublicAssetUrl(documents.value.find((document) => document.url)?.url || '', runtimeConfig.public.apiBaseUrl)
})

async function loadBooking() {
  if (!bookingToken.value) {
    bookingData.value = null
    loadError.value = ui.value.track.couldNotLoadBooking
    isLoading.value = false
    return
  }

  isLoading.value = true
  loadError.value = ''

  try {
    bookingData.value = await fetchBooking(bookingToken.value)
  } catch (error) {
    console.error('Failed to load public booking', error)
    bookingData.value = null
    loadError.value = resolvePublicApiError(error, ui.value.track.couldNotLoadBookingConfirmation, locale.value)
  } finally {
    isLoading.value = false
  }
}

async function handlePrimaryAction() {
  checkoutError.value = ''

  if (isPrimaryActionDisabled.value) {
    return
  }

  if (!paymentSummary.value) {
    await navigateTo(buildRentSearchRoute({}, {
      locale: locale.value,
    }))
    return
  }

  if (hasReusableCheckoutLink.value && latestSession.value?.redirectUrl && import.meta.client) {
    window.location.href = latestSession.value.redirectUrl
    return
  }

  isStartingCheckout.value = true

  try {
    const checkout = await createCheckout(bookingToken.value)

    if (checkout?.redirectUrl && import.meta.client) {
      window.location.href = checkout.redirectUrl
      return
    }

    throw new Error(ui.value.track.couldNotStartPayment)
  } catch (error) {
    console.error('Failed to start public checkout', error)
    checkoutError.value = resolvePublicApiError(error, ui.value.track.couldNotStartPayment, locale.value)
  } finally {
    isStartingCheckout.value = false
  }
}

watch(
  bookingToken,
  async () => {
    await loadBooking()
  },
  { immediate: true },
)

onMounted(() => {
  window.scrollTo(0, 0)
})
</script>

<template>
  <div class="min-h-screen relative flex flex-col font-sans selection:bg-brand-orange/30">
    <div class="container mx-auto px-4 relative z-10 pt-12 pb-24 flex-1 flex flex-col items-center justify-center">
      <div v-if="isLoading" class="max-w-3xl w-full mx-auto">
        <div class="bg-white/60 backdrop-blur-3xl border border-white/80 shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] rounded-[3rem] p-10 md:p-14 text-center">
          <motion.div
            :animate="{ rotate: 360 }"
            :transition="{ duration: 1, repeat: Infinity, ease: 'linear' }"
            class="w-12 h-12 border-4 border-brand-orange/20 border-t-brand-orange rounded-full mx-auto mb-6"
          />
          <h1 class="text-4xl font-display font-bold text-slate-900 mb-3">{{ ui.track.loadingConfirmation }}</h1>
          <p class="text-slate-500">{{ ui.track.loadingDescription }}</p>
        </div>
      </div>

      <div v-else-if="loadError || !booking" class="max-w-3xl w-full mx-auto">
        <div class="bg-white/60 backdrop-blur-3xl border border-white/80 shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] rounded-[3rem] p-10 md:p-14 text-center">
          <div class="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-red-50 text-red-500 text-sm font-bold uppercase tracking-widest mb-6 border border-white/60 shadow-sm backdrop-blur-md">
            <Star class="w-4 h-4" /> {{ ui.track.confirmationUnavailable }}
          </div>
          <h1 class="text-4xl font-display font-bold text-slate-900 mb-4">{{ ui.track.couldNotLoadBooking }}</h1>
          <p class="text-lg text-slate-600 max-w-2xl mx-auto leading-relaxed mb-8">
            {{ loadError || ui.track.couldNotLoadBooking }}
          </p>
          <button
            type="button"
            class="px-10 py-5 bg-slate-900 text-white rounded-2xl font-bold text-lg hover:bg-brand-orange transition-all"
            @click="navigateTo(localizedPath('/'))"
          >
            {{ ui.track.backToHome }}
          </button>
        </div>
      </div>

      <div v-else class="max-w-4xl w-full mx-auto">
        <div class="text-center mb-12">
          <motion.div
            :initial="{ scale: 0, rotate: -180 }"
            :animate="{ scale: 1, rotate: 0 }"
            :transition="{ type: 'spring', stiffness: 200, damping: 20, delay: 0.1 }"
            class="w-28 h-28 bg-gradient-to-br from-emerald-400 to-emerald-600 rounded-[2rem] flex items-center justify-center mx-auto mb-8 shadow-[0_20px_40px_-10px_rgba(16,185,129,0.5)] border border-white/50 rotate-3"
          >
            <Check class="w-14 h-14 text-white drop-shadow-md" :stroke-width="3" />
          </motion.div>

          <motion.div
            :initial="{ opacity: 0, y: 20 }"
            :animate="{ opacity: 1, y: 0 }"
            :transition="{ delay: 0.2 }"
            class="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-brand-orange/10 text-brand-orange text-sm font-bold uppercase tracking-widest mb-6 border border-white/60 shadow-sm backdrop-blur-md"
          >
            <Star class="w-4 h-4" fill="currentColor" /> {{ ui.track.impeccableChoice }}
          </motion.div>

          <motion.h1
            :initial="{ opacity: 0, y: 20 }"
            :animate="{ opacity: 1, y: 0 }"
            :transition="{ delay: 0.3 }"
            class="text-4xl md:text-6xl font-display font-bold text-slate-900 mb-6 tracking-tight"
          >
            {{ titleCopy }}
          </motion.h1>

          <motion.p
            :initial="{ opacity: 0, y: 20 }"
            :animate="{ opacity: 1, y: 0 }"
            :transition="{ delay: 0.4 }"
            class="text-lg md:text-xl text-slate-600 max-w-2xl mx-auto leading-relaxed"
          >
            {{ descriptionCopy }}
          </motion.p>
        </div>

        <motion.div
          :initial="{ opacity: 0, y: 40 }"
          :animate="{ opacity: 1, y: 0 }"
          :transition="{ delay: 0.5, duration: 0.6, ease: [0.22, 1, 0.36, 1] }"
          class="bg-white/60 backdrop-blur-3xl border border-white/80 shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] rounded-[3rem] p-8 md:p-12 mb-10 relative overflow-hidden"
        >
          <div class="absolute inset-0 bg-gradient-to-br from-white/60 via-white/10 to-transparent pointer-events-none" />

          <div class="relative z-10">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-10 pb-10 border-b border-white/60">
              <div>
                <p class="text-xs font-bold text-slate-400 uppercase tracking-widest mb-2">{{ ui.track.bookingReference }}</p>
                <p class="text-3xl font-display font-bold text-slate-900 tracking-tight">{{ booking.reference }}</p>
              </div>

              <div v-if="downloadDocumentUrl" class="mt-6 md:mt-0">
                <a
                  :href="downloadDocumentUrl"
                  class="flex items-center gap-2 px-6 py-3 bg-white/80 hover:bg-white backdrop-blur-xl border border-white shadow-sm hover:shadow-md rounded-2xl text-slate-700 font-bold transition-all group"
                  target="_blank"
                  rel="noreferrer"
                >
                  <Download class="w-4 h-4 group-hover:-translate-y-0.5 transition-transform" />
                  {{ ui.track.downloadDocuments }}
                </a>
              </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-12">
              <div class="space-y-8">
                <div>
                  <h3 class="text-lg font-display font-bold text-slate-900 mb-6 flex items-center gap-3">
                    <div class="w-10 h-10 bg-white/80 rounded-xl flex items-center justify-center text-slate-900 shadow-sm border border-white">
                      <Car class="w-5 h-5" />
                    </div>
                    {{ ui.track.yourVehicle }}
                  </h3>

                  <div class="bg-white/50 backdrop-blur-md rounded-[2rem] p-4 border border-white/80 shadow-sm group overflow-hidden relative">
                    <div class="aspect-[16/9] rounded-2xl overflow-hidden mb-4 relative">
                      <img
                        v-if="vehicleImageUrl"
                        :src="vehicleImageUrl"
                        :alt="vehicleName || ui.track.bookedVehicleFallbackAlt"
                        class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-700"
                      >
                      <div
                        v-else
                        class="w-full h-full bg-slate-100 text-slate-400 flex items-center justify-center"
                      >
                        <Car class="w-10 h-10" />
                      </div>
                      <div class="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent opacity-60" />
                    </div>

                    <div class="px-2 pb-2">
                      <p v-if="vehicleCategory" class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">{{ vehicleCategory }}</p>
                      <p class="text-xl font-display font-bold text-slate-900">{{ vehicleName || '-' }}</p>
                    </div>
                  </div>
                </div>
              </div>

              <div class="space-y-8">
                <div>
                  <h3 class="text-lg font-display font-bold text-slate-900 mb-6 flex items-center gap-3">
                    <div class="w-10 h-10 bg-white/80 rounded-xl flex items-center justify-center text-blue-500 shadow-sm border border-white">
                      <Calendar class="w-5 h-5" />
                    </div>
                    {{ ui.track.itinerary }}
                  </h3>

                  <div class="bg-white/50 backdrop-blur-md rounded-[2rem] p-6 md:p-8 border border-white/80 shadow-sm">
                    <div class="space-y-8 relative before:absolute before:inset-y-8 before:left-[19px] before:w-0.5 before:bg-white/80 before:shadow-sm">
                      <div class="flex gap-6 relative z-10">
                        <div class="w-10 h-10 bg-white rounded-full border-2 border-white shadow-md flex items-center justify-center shrink-0">
                          <div class="w-3 h-3 bg-slate-900 rounded-full" />
                        </div>

                        <div class="pt-1">
                          <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">{{ ui.track.pickup }}</p>
                          <p class="text-slate-900 font-bold text-lg">{{ booking.pickup?.dateLabel }}, {{ booking.pickup?.timeLabel }}</p>
                          <p class="text-slate-600 text-sm mt-1.5 flex items-center gap-1.5 font-medium">
                            <MapPin class="w-4 h-4 text-brand-orange" /> {{ booking.pickup?.location }}
                          </p>
                        </div>
                      </div>

                      <div class="flex gap-6 relative z-10">
                        <div class="w-10 h-10 bg-white rounded-full border-2 border-white shadow-md flex items-center justify-center shrink-0">
                          <div class="w-3 h-3 bg-brand-orange rounded-full" />
                        </div>

                        <div class="pt-1">
                          <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">{{ ui.track.dropoff }}</p>
                          <p class="text-slate-900 font-bold text-lg">{{ booking.dropoff?.dateLabel }}, {{ booking.dropoff?.timeLabel }}</p>
                          <p class="text-slate-600 text-sm mt-1.5 flex items-center gap-1.5 font-medium">
                            <MapPin class="w-4 h-4 text-brand-orange" /> {{ booking.dropoff?.location }}
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

      <div v-if="hasConfiguredPrepayment" class="bg-emerald-50/50 backdrop-blur-md rounded-[2rem] p-6 border border-emerald-100/50 flex items-center justify-between">
        <div>
          <p class="text-[10px] font-bold text-emerald-600/70 uppercase tracking-widest mb-1">{{ paymentLabel }}</p>
          <p class="text-3xl font-display font-bold text-emerald-600 tracking-tight">{{ formatMoney(paymentAmount, booking.financials?.currency) }}</p>
        </div>

                  <div class="w-12 h-12 bg-emerald-100 rounded-full flex items-center justify-center">
                    <Shield class="w-6 h-6 text-emerald-500" />
                  </div>
                </div>

                <div
                  v-if="hasConfiguredPrepayment"
                  :class="['backdrop-blur-md rounded-[2rem] p-5 border', paymentStateTheme.wrapper]"
                >
                  <p :class="['text-xs font-bold uppercase tracking-widest mb-2', paymentStateTheme.eyebrow]">
                    {{ providerLabel }} {{ ui.track.providerPaymentSuffix }}
                  </p>
                  <p class="text-sm leading-relaxed">
                    {{ paymentMessage }}
                  </p>
                  <p v-if="hasReusableCheckoutLink" class="text-sm leading-relaxed mt-3">
                    {{ ui.track.paymentLinkReady }}
                  </p>
                  <p v-if="latestSession?.expiresAt" class="text-xs uppercase tracking-widest mt-4 opacity-70">
                    {{ ui.track.sessionExpiresPrefix }} {{ formatDateTime(latestSession.expiresAt) }}
                  </p>
                  <p v-if="latestSession?.errorMessage" class="text-sm leading-relaxed mt-3">
                    {{ latestSession.errorMessage }}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </motion.div>

        <div v-if="checkoutError" class="mb-6 bg-red-50/80 backdrop-blur-sm rounded-2xl p-4 flex gap-3 text-red-600 text-sm font-medium border border-red-100/70 justify-center">
          <Shield class="w-5 h-5 shrink-0" />
          <p>{{ checkoutError }}</p>
        </div>

        <motion.div
          :initial="{ opacity: 0, y: 20 }"
          :animate="{ opacity: 1, y: 0 }"
          :transition="{ delay: 0.7 }"
          class="flex flex-col sm:flex-row items-center justify-center gap-4"
        >
          <button
            type="button"
            :class="primaryActionClasses"
            :disabled="isPrimaryActionDisabled"
            @click="handlePrimaryAction"
          >
            <span>{{ isStartingCheckout ? ui.track.openingPayment : primaryActionLabel }}</span>
            <component :is="primaryActionIcon" class="w-5 h-5 group-hover:translate-x-1 transition-transform" />
          </button>

          <button
            type="button"
            class="w-full sm:w-auto px-10 py-5 bg-white/60 hover:bg-white backdrop-blur-xl border border-white/80 text-slate-900 rounded-2xl font-bold text-lg transition-all shadow-sm hover:shadow-md"
            @click="navigateTo(localizedPath('/'))"
          >
            {{ ui.track.backToHome }}
          </button>
        </motion.div>
      </div>
    </div>
  </div>
</template>
