<script setup>
import { AnimatePresence, motion } from 'motion-v'
import { Calendar, Check, Clock, Globe, MapPin, MessageSquare, Phone, Shield, Sparkles, User, X } from 'lucide-vue-next'
import { format, startOfDay } from 'date-fns'
import LuxuryCarCard from '~/components/luxury/LuxuryCarCard.vue'
import AppCalendar from '~/components/shared/AppCalendar.vue'
import { buildLuxuryPageSeo, useLuxuryContent } from '~/content/luxury'
import { resolvePublicApiError } from '~/content/utils'
import { buildPublicSeoLinks } from '~/utils/public-seo'

definePageMeta({
  siteHeaderTheme: 'dark',
  siteHeaderOverlay: true,
})

const featureIcons = {
  shield: Shield,
  clock: Clock,
  sparkles: Sparkles,
}
const {
  luxuryCars,
  luxuryFeatures,
  luxuryForm,
  luxuryPage,
  luxuryUi,
} = useLuxuryContent()
const runtimeConfig = useRuntimeConfig()
const route = useRoute()
const router = useRouter()
const pageOrigin = computed(() => String(runtimeConfig.public.siteBaseUrl || '').replace(/\/+$/, ''))
const luxuryPageSeo = computed(() => buildLuxuryPageSeo(luxuryPage.value, pageOrigin.value))
const ui = usePublicUi()
const { locale } = usePublicLocale()
const luxurySystemUi = {
  successTitle: ui.value.common.requestSent,
  successDescription: ui.value.common.requestSentDescription,
  submitErrorLabel: ui.value.common.couldNotSubmitRequest,
}

useSeoMeta({
  title: () => luxuryPageSeo.value?.title || '',
  description: () => luxuryPageSeo.value?.description || '',
  ogTitle: () => luxuryPageSeo.value?.ogTitle || '',
  ogDescription: () => luxuryPageSeo.value?.ogDescription || '',
  ogImage: () => luxuryPageSeo.value?.ogImage || '',
  robots: () => luxuryPageSeo.value?.robots || 'index,follow',
})

useHead(() => ({
  link: buildPublicSeoLinks(luxuryPageSeo.value),
}))

const selectedCar = ref(null)
const showDatePicker = ref(false)
const dateRange = ref()
const submitState = ref('idle')
const submitError = ref('')
const submitAttempted = ref(false)
const formData = reactive({
  name: '',
  location: '',
  notes: '',
})
const {
  combinePhone,
  handlePhoneChange,
  handlePhoneCountryCodeChange,
  isPhoneValid,
  phoneCountryCode,
  phoneNumber,
  resetPhone,
} = useInternationalPhone()
const { submitLead } = usePublicLead()

const isFormValid = computed(() => {
  return formData.name.trim() !== ''
    && isPhoneValid.value
    && formData.location.trim() !== ''
    && dateRange.value?.from
})

watch(
  isFormValid,
  (value) => {
    if (value && submitError.value === ui.value.common.fillRequiredFields) {
      submitError.value = ''
    }
  },
)

function fieldClass(value, invalid = false) {
  const hasError = submitAttempted.value && (String(value || '').trim() === '' || invalid)
  return hasError
    ? 'border-red-500 focus:border-red-500'
    : 'border-white/20 focus:border-white'
}

const legacyLuxuryId = computed(() => {
  const routeParam = route.params?.legacyLuxuryId

  if (typeof routeParam === 'string' && routeParam.trim()) {
    return routeParam.trim()
  }

  return String(route.query.legacyLuxuryId || '').trim()
})

const selectedLegacyCar = computed(() => {
  if (!legacyLuxuryId.value) {
    return null
  }

  return luxuryCars.value.find((car) => String(car.legacyLuxuryId || '') === legacyLuxuryId.value) || null
})

function clearLegacyLuxuryQuery() {
  if (route.params?.legacyLuxuryId) {
    const nextQuery = { ...route.query }
    delete nextQuery.legacyLuxuryId

    router.replace({
      path: luxuryPage.value?.path || '/luxury',
      query: nextQuery,
    })
    return
  }

  if (!route.query.legacyLuxuryId) {
    return
  }

  const nextQuery = { ...route.query }
  delete nextQuery.legacyLuxuryId

  router.replace({ query: nextQuery })
}

function resetLuxuryForm() {
  formData.name = ''
  formData.location = ''
  formData.notes = ''
  dateRange.value = undefined
  resetPhone()
  submitAttempted.value = false
}

function closeLuxuryModal() {
  selectedCar.value = null
  showDatePicker.value = false
  submitState.value = 'idle'
  submitError.value = ''
  resetLuxuryForm()
  clearLegacyLuxuryQuery()
}

function buildLuxuryLeadMessage() {
  const lines = []

  if (selectedCar.value?.name) {
    lines.push(`Vehicle: ${selectedCar.value.name}`)
  }

  if (dateRange.value?.from) {
    const rangeLabel = dateRange.value?.to
      ? `${format(dateRange.value.from, 'MMM d, yyyy')} - ${format(dateRange.value.to, 'MMM d, yyyy')}`
      : format(dateRange.value.from, 'MMM d, yyyy')

    lines.push(`Dates: ${rangeLabel}`)
  }

  if (formData.location.trim()) {
    lines.push(`Delivery location: ${formData.location.trim()}`)
  }

  if (formData.notes.trim()) {
    lines.push(`Notes: ${formData.notes.trim()}`)
  }

  return lines.join('\n')
}

async function handleSubmit() {
  submitAttempted.value = true

  if (!isFormValid.value) {
    submitError.value = ui.value.common.fillRequiredFields
    return
  }

  submitState.value = 'submitting'
  submitError.value = ''

  try {
    await submitLead({
      form: 'luxury',
      name: formData.name.trim(),
      phone: combinePhone(),
      subject: selectedCar.value?.name ? `Luxury request · ${selectedCar.value.name}` : 'Luxury request',
      preferred_vehicle: selectedCar.value?.name || null,
      message: buildLuxuryLeadMessage(),
      meta: {
        vehicle_slug: selectedCar.value?.slug || selectedCar.value?.id || null,
        requested_dates: dateRange.value?.from
          ? {
              from: dateRange.value.from.toISOString(),
              to: dateRange.value?.to ? dateRange.value.to.toISOString() : null,
            }
          : null,
        delivery_location: formData.location.trim(),
      },
    })

    submitState.value = 'success'
  } catch (error) {
    submitState.value = 'idle'
    submitError.value = resolvePublicApiError(error, luxurySystemUi.submitErrorLabel, locale.value)
  }
}

watch(selectedLegacyCar, (car) => {
  if (!car) {
    return
  }

  selectedCar.value = car
}, { immediate: true })
</script>

<template>
  <div class="min-h-screen bg-[#030303] text-white font-sans selection:bg-white/20">
    <main>
      <section class="relative h-screen flex items-center justify-center overflow-hidden">
        <motion.div
          :initial="{ scale: 1.1, opacity: 0 }"
          :animate="{ scale: 1, opacity: 1 }"
          :transition="{ duration: 1.5, ease: 'easeOut' }"
          class="absolute inset-0"
        >
          <img
            :src="luxuryPage?.heroImage || luxuryPage?.featuredImage"
            :alt="luxuryPage?.title"
            class="w-full h-full object-cover"
            referrerpolicy="no-referrer"
          >
          <div class="absolute inset-0 bg-gradient-to-b from-black/40 via-black/20 to-[#030303]" />
        </motion.div>

        <div class="relative z-10 text-center px-6 mt-20">
          <motion.div
            :initial="{ opacity: 0, y: 30 }"
            :animate="{ opacity: 1, y: 0 }"
            :transition="{ duration: 1, delay: 0.5, ease: [0.16, 1, 0.3, 1] }"
          >
            <div class="text-[10px] sm:text-xs tracking-[0.3em] uppercase text-white/70 mb-6 sm:mb-8 font-medium">
              {{ luxuryUi.collectionLabel }}
            </div>
            <h1 class="text-5xl sm:text-7xl md:text-8xl lg:text-9xl font-luxury font-light tracking-tighter leading-[0.9] mb-8 uppercase">
              {{ luxuryPage?.title }} <br class="hidden sm:block">
              <span class="text-white/90 font-medium">{{ luxuryPage?.subtitle }}</span>
            </h1>
            <p class="text-white/50 text-sm sm:text-base max-w-md mx-auto font-light leading-relaxed">
              {{ luxuryPage?.excerpt }}
            </p>

          </motion.div>
        </div>

        <motion.div
          :initial="{ opacity: 0 }"
          :animate="{ opacity: 1 }"
          :transition="{ delay: 1.5, duration: 1 }"
          class="absolute bottom-12 left-1/2 -translate-x-1/2 flex flex-col items-center gap-4"
        >
          <div class="text-[9px] tracking-[0.3em] uppercase text-white/40">{{ luxuryUi.scrollLabel }}</div>
          <div class="w-px h-12 bg-gradient-to-b from-white/40 to-transparent" />
        </motion.div>
      </section>

      <section class="py-24 px-4 sm:px-6 max-w-6xl mx-auto">
        <div v-if="luxuryCars.length" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          <LuxuryCarCard
            v-for="(car, idx) in luxuryCars"
            :key="car.id"
            :car="car"
            :delay="(idx % 4) * 0.1"
            @select="selectedCar = $event"
          />
        </div>
        <div
          v-else
          class="rounded-sm border border-white/10 bg-white/[0.02] px-8 py-16 text-center"
        >
          <h2 class="text-3xl font-luxury uppercase tracking-widest font-light mb-4">{{ luxuryUi.fleetEmptyTitle }}</h2>
          <p class="text-white/50 max-w-2xl mx-auto text-sm leading-relaxed">{{ luxuryUi.fleetEmptyDescription }}</p>
        </div>
      </section>

      <section class="py-32 px-6 bg-[#080808] border-t border-white/5">
        <div class="max-w-6xl mx-auto">
          <div class="text-center mb-20">
            <h2 class="text-3xl sm:text-4xl font-luxury uppercase tracking-widest font-light mb-6">{{ luxuryUi.conciergeTitle }}</h2>
            <p class="text-white/40 max-w-lg mx-auto font-light text-sm">
              {{ luxuryUi.conciergeDescription }}
            </p>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-3 gap-12">
            <motion.div
              v-for="(feature, idx) in luxuryFeatures"
              :key="feature.title"
              :initial="{ opacity: 0, y: 30 }"
              :while-in-view="{ opacity: 1, y: 0 }"
              :viewport="{ once: true }"
              :transition="{ duration: 0.8, delay: idx * 0.2, ease: 'easeOut' }"
              class="text-center"
            >
              <div class="w-16 h-16 mx-auto rounded-full border border-white/10 flex items-center justify-center mb-6 bg-white/[0.02]">
                <component :is="featureIcons[feature.iconKey]" class="w-6 h-6 text-white/60" :stroke-width="1" />
              </div>
              <h4 class="text-sm font-medium tracking-widest uppercase mb-4">{{ feature.title }}</h4>
              <p class="text-white/40 text-sm font-light leading-relaxed">
                {{ feature.desc }}
              </p>
            </motion.div>
          </div>
        </div>
      </section>
    </main>

    <AnimatePresence>
      <div v-if="selectedCar" class="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6">
        <motion.div
          :initial="{ opacity: 0 }"
          :animate="{ opacity: 1 }"
          :exit="{ opacity: 0 }"
          class="absolute inset-0 bg-black/90 backdrop-blur-xl"
          @click="closeLuxuryModal"
        />

        <motion.div
          :initial="{ opacity: 0, y: 40, scale: 0.95 }"
          :animate="{ opacity: 1, y: 0, scale: 1 }"
          :exit="{ opacity: 0, y: 20, scale: 0.95 }"
          :transition="{ duration: 0.5, ease: [0.16, 1, 0.3, 1] }"
          class="relative w-full max-w-4xl bg-[#050505] border border-white/10 rounded-sm overflow-hidden shadow-2xl flex flex-col md:flex-row max-h-[90vh]"
        >
          <button
            class="absolute top-6 right-6 z-20 w-10 h-10 bg-black/20 backdrop-blur-md rounded-full border border-white/10 flex items-center justify-center text-white/60 hover:text-white hover:bg-white/10 transition-all"
            @click="closeLuxuryModal"
          >
            <X class="w-4 h-4" />
          </button>

          <div class="w-full md:w-2/5 h-48 md:h-auto relative shrink-0">
            <img :src="selectedCar.image" :alt="selectedCar.name" class="w-full h-full object-cover">
            <div class="absolute inset-0 bg-gradient-to-t md:bg-gradient-to-r from-[#050505] to-transparent" />
            <div class="absolute bottom-8 left-8 right-8">
              <div class="text-[9px] tracking-[0.2em] uppercase text-white/50 mb-2">{{ luxuryUi.modalEyebrow }}</div>
              <h2 class="font-luxury text-2xl uppercase tracking-widest font-light">{{ selectedCar.name }}</h2>
            </div>
          </div>

          <div class="w-full md:w-3/5 p-8 md:p-12 overflow-y-auto custom-scrollbar">
            <div v-if="submitState === 'success'" class="h-full min-h-[420px] flex flex-col items-center justify-center text-center">
              <div class="w-20 h-20 rounded-full border border-white/10 bg-white/[0.03] flex items-center justify-center mb-8">
                <Check class="w-8 h-8 text-white" />
              </div>
              <div class="text-[10px] tracking-[0.25em] uppercase text-white/40 mb-4">{{ luxuryUi.modalEyebrow }}</div>
              <h3 class="text-2xl font-light tracking-wide mb-4">{{ luxurySystemUi.successTitle }}</h3>
              <p class="text-white/40 text-sm font-light leading-relaxed max-w-md mb-10">
                {{ luxurySystemUi.successDescription }}
              </p>
              <button
                type="button"
                class="px-8 py-3 bg-white text-black rounded-sm text-[11px] font-medium uppercase tracking-[0.2em] hover:bg-white/90 transition-colors"
                @click="closeLuxuryModal"
              >
                {{ luxuryForm.doneLabel }}
              </button>
            </div>

            <form v-else novalidate class="space-y-8" @submit.prevent="handleSubmit">
              <div class="mb-10">
                <h3 class="text-lg font-light tracking-wide mb-2">{{ luxuryUi.modalTitle }}</h3>
                <p class="text-white/40 text-sm font-light leading-relaxed">
                  {{ luxuryUi.modalDescription }}
                </p>
              </div>

              <div class="grid grid-cols-1 sm:grid-cols-2 gap-8">
                <div class="relative">
                  <input
                    id="name"
                    v-model="formData.name"
                    required
                    type="text"
                    :class="['peer w-full bg-transparent border-b py-2 text-sm text-white placeholder-transparent focus:outline-none transition-colors', fieldClass(formData.name)]"
                    :placeholder="luxuryForm.placeholders.name"
                  >
                  <label for="name" :class="[
                    'absolute left-0 -top-3.5 text-[10px] tracking-widest uppercase transition-all peer-placeholder-shown:text-sm peer-placeholder-shown:top-2 peer-focus:-top-3.5 peer-focus:text-[10px]',
                    submitAttempted && formData.name.trim() === '' ? 'text-red-500 peer-placeholder-shown:text-red-300 peer-focus:text-red-500' : 'text-white/40 peer-placeholder-shown:text-white/30 peer-focus:text-white/60',
                  ]">
                    {{ luxuryForm.labels.name }}
                  </label>
                </div>
                <div class="relative">
                  <label
                    :class="[
                      'absolute left-0 -top-3.5 text-[10px] tracking-widest uppercase transition-all',
                      submitAttempted && (!phoneNumber || !isPhoneValid)
                        ? 'text-red-500'
                        : 'text-white/40',
                    ]"
                  >
                    {{ luxuryForm.labels.phone }}
                  </label>
                  <div class="grid grid-cols-[6rem_minmax(0,1fr)] gap-4 items-end">
                    <input
                      :value="phoneCountryCode"
                      type="tel"
                      inputmode="tel"
                      autocomplete="tel-country-code"
                      required
                      :class="['w-full bg-transparent border-b py-2 text-sm text-white placeholder-white/30 focus:outline-none transition-colors text-center font-medium', fieldClass(phoneCountryCode, phoneCountryCode === '+')]"
                      placeholder="+995"
                      @input="handlePhoneCountryCodeChange"
                    >
                    <input
                      id="phone"
                      :value="phoneNumber"
                      required
                      type="tel"
                      inputmode="tel"
                      autocomplete="tel-national"
                      :class="['w-full bg-transparent border-b py-2 text-sm text-white placeholder-transparent focus:outline-none transition-colors', fieldClass(phoneNumber, !isPhoneValid)]"
                      :placeholder="luxuryForm.placeholders.phone"
                      @input="handlePhoneChange"
                    >
                  </div>
                  <p v-if="submitAttempted && (!phoneNumber || !isPhoneValid)" class="absolute -bottom-5 left-0 text-[10px] text-red-500">
                    {{ luxuryForm.phoneValidationMessage }}
                  </p>
                </div>
              </div>

              <div class="grid grid-cols-1 sm:grid-cols-2 gap-8">
                <div class="relative">
                  <div
                    :class="[
                      'w-full bg-transparent border-b py-2 text-sm text-white cursor-pointer hover:border-white transition-colors flex items-center justify-between',
                      submitAttempted && !dateRange?.from ? 'border-red-500' : 'border-white/20',
                    ]"
                    @click="showDatePicker = !showDatePicker"
                  >
                    <span :class="dateRange?.from ? 'text-white' : 'text-white/30'">
                      {{
                        dateRange?.from
                          ? (dateRange.to ? `${format(dateRange.from, 'MMM d')} - ${format(dateRange.to, 'MMM d')}` : format(dateRange.from, 'MMM d'))
                          : luxuryForm.placeholders.dates
                      }}
                    </span>
                    <Calendar class="w-4 h-4 text-white/40" />
                  </div>
                  <label class="absolute left-0 -top-3.5 text-[10px] tracking-widest uppercase text-white/60">{{ luxuryForm.labels.dates }}</label>

                  <AnimatePresence>
                    <motion.div
                      v-if="showDatePicker"
                      :initial="{ opacity: 0, y: 10 }"
                      :animate="{ opacity: 1, y: 0 }"
                      :exit="{ opacity: 0, y: 10 }"
                      class="absolute top-full left-0 mt-2 bg-[#111] border border-white/10 rounded-2xl p-4 z-50 shadow-2xl dark w-max"
                    >
                      <AppCalendar
                        mode="range"
                        :selected="dateRange"
                        :number-of-months="1"
                        :disabled="{ before: startOfDay(new Date()) }"
                        class="font-sans"
                        @select="dateRange = $event"
                      />
                      <div class="mt-4 flex justify-end">
                        <button
                          type="button"
                          class="px-4 py-2 bg-white text-black rounded-lg text-xs font-bold hover:bg-white/90 transition-colors"
                          @click="showDatePicker = false"
                        >
                          {{ luxuryForm.doneLabel }}
                        </button>
                      </div>
                    </motion.div>
                  </AnimatePresence>
                </div>
                <div class="relative">
                  <input
                    id="location"
                    v-model="formData.location"
                    required
                    type="text"
                    :class="['peer w-full bg-transparent border-b py-2 text-sm text-white placeholder-transparent focus:outline-none transition-colors', fieldClass(formData.location)]"
                    :placeholder="luxuryForm.placeholders.location"
                  >
                  <label for="location" :class="[
                    'absolute left-0 -top-3.5 text-[10px] tracking-widest uppercase transition-all peer-placeholder-shown:text-sm peer-placeholder-shown:top-2 peer-focus:-top-3.5 peer-focus:text-[10px]',
                    submitAttempted && formData.location.trim() === '' ? 'text-red-500 peer-placeholder-shown:text-red-300 peer-focus:text-red-500' : 'text-white/40 peer-placeholder-shown:text-white/30 peer-focus:text-white/60',
                  ]">
                    {{ luxuryForm.labels.location }}
                  </label>
                </div>
              </div>

              <div class="relative pt-4">
                <textarea
                  id="notes"
                  v-model="formData.notes"
                  class="peer w-full bg-transparent border-b border-white/20 py-2 text-sm text-white placeholder-transparent focus:outline-none focus:border-white transition-colors min-h-[80px] resize-none"
                  :placeholder="luxuryForm.placeholders.notes"
                />
                <label for="notes" class="absolute left-0 -top-0 text-[10px] tracking-widest uppercase text-white/40 transition-all peer-placeholder-shown:text-sm peer-placeholder-shown:text-white/30 peer-placeholder-shown:top-2 peer-focus:-top-0 peer-focus:text-[10px] peer-focus:text-white/60">
                  {{ luxuryForm.labels.notes }}
                </label>
              </div>

              <div class="pt-8">
                <button
                  type="submit"
                  :disabled="submitState === 'submitting'"
                  class="w-full py-4 text-[11px] tracking-[0.2em] font-medium uppercase transition-colors bg-brand-orange text-white hover:bg-[#E66000] disabled:pointer-events-none"
                >
                  <span class="inline-flex items-center justify-center gap-3">
                    <span v-if="submitState === 'submitting'" class="w-4.5 h-4.5 border-2 border-white/40 border-t-white rounded-full animate-spin" />
                    {{ submitState === 'submitting' ? luxuryForm.submittingLabel : luxuryForm.submitLabel }}
                  </span>
                </button>
                <p v-if="submitAttempted && !isFormValid" class="mt-4 rounded-2xl border border-red-500/20 bg-red-500/10 px-4 py-3 text-xs text-red-200">
                  {{ submitError || ui.common.fillRequiredFields }}
                </p>
                <p v-if="submitError && submitError !== ui.common.fillRequiredFields" class="mt-4 text-xs text-red-400 leading-relaxed">
                  {{ submitError }}
                </p>
              </div>
            </form>
          </div>
        </motion.div>
      </div>
    </AnimatePresence>
  </div>
</template>
