<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { format } from 'date-fns'
import { Calendar, MapPin, MessageCircle, Search } from 'lucide-vue-next'
import { normalizeCityRentalHref } from '~/components/city-rental/link-utils'
import { buildRentSearchRoute, buildRentTripQuery } from '~/utils/public-routes'

const props = defineProps({
  stickyBar: {
    type: Object,
    required: true,
  },
})

const { locale } = usePublicLocale()
const { buildDate } = usePublicDateDefaults()
const activePopover = useState('city-rental-search-active-popover', () => null)
const pickupLocation = useState('city-rental-search-pickup-location', () => null)
const searchDateRange = useState('city-rental-search-date-range', () => ({
  from: buildDate(3),
  to: buildDate(10),
}))
const stickyBar = computed(() => props.stickyBar || {})
const whatsappUrl = computed(() => normalizeCityRentalHref(stickyBar.value?.whatsappUrl))
const mobileWhatsappUrl = computed(() => normalizeCityRentalHref(stickyBar.value?.mobileWhatsappUrl || stickyBar.value?.whatsappUrl))
const isVisible = ref(false)
const pickupValueLabel = computed(() => pickupLocation.value?.name || stickyBar.value?.pickupValue || '')
const datesValueLabel = computed(() => {
  const from = searchDateRange.value?.from
  const to = searchDateRange.value?.to

  if (from && to) {
    return `${format(from, 'MMM d, yyyy')} - ${format(to, 'MMM d, yyyy')}`
  }

  if (from) {
    return format(from, 'MMM d, yyyy')
  }

  return stickyBar.value?.datesValue || ''
})
const canBuildSearch = computed(() => Boolean(pickupLocation.value?.backendId && searchDateRange.value?.from && searchDateRange.value?.to))
const stickySearchTarget = computed(() => {
  if (!canBuildSearch.value) {
    return ''
  }

  const pickupAt = new Date(searchDateRange.value.from)
  pickupAt.setHours(12, 30, 0, 0)
  const dropoffAt = new Date(searchDateRange.value.to)
  dropoffAt.setHours(8, 30, 0, 0)

  return buildRentSearchRoute(buildRentTripQuery({
    pickupLocationId: pickupLocation.value.backendId,
    dropoffLocationId: pickupLocation.value.backendId,
    pickupAt: pickupAt.toISOString(),
    dropoffAt: dropoffAt.toISOString(),
    returnToSameLocation: '1',
  }), {
    locale: locale.value,
  })
})

function handleScroll() {
  isVisible.value = window.scrollY > 600
}

function openHeroSearch(popover) {
  activePopover.value = popover

  document.getElementById('city-rental-search')?.scrollIntoView({
    behavior: 'smooth',
    block: 'center',
  })
}

async function handleSearchClick() {
  if (stickySearchTarget.value) {
    await navigateTo(stickySearchTarget.value)
    return
  }

  openHeroSearch('pickup')
}

onMounted(() => {
  handleScroll()
  window.addEventListener('scroll', handleScroll, { passive: true })
})

onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<template>
  <Transition name="sticky-top">
    <div v-if="isVisible" class="fixed top-0 left-0 w-full z-50 hidden md:block">
      <div class="bg-white/80 backdrop-blur-xl border-b border-slate-200 shadow-sm px-4 py-3">
        <div class="max-w-7xl mx-auto flex items-center justify-between gap-4">
          <div class="flex items-center gap-4 flex-1">
            <div class="font-display font-bold text-slate-900 border-r border-slate-200 pr-4">
              {{ stickyBar.title }}
            </div>

            <div class="flex bg-slate-50 border border-slate-200 rounded-xl overflow-hidden flex-1 max-w-xl">
              <button
                type="button"
                class="flex-1 flex items-center gap-2 px-4 py-2 text-sm text-slate-700 hover:bg-white transition-colors border-r border-slate-200"
                @click="openHeroSearch('pickup')"
              >
                <MapPin class="w-4 h-4 text-brand-orange" />
                {{ pickupValueLabel }}
              </button>
              <button
                type="button"
                class="flex-1 flex items-center gap-2 px-4 py-2 text-sm text-slate-700 hover:bg-white transition-colors"
                @click="openHeroSearch('dates')"
              >
                <Calendar class="w-4 h-4 text-brand-orange" />
                {{ datesValueLabel }}
              </button>
              <button
                type="button"
                :class="[
                  'bg-slate-900 text-white px-6 py-2 text-sm font-bold hover:bg-slate-800 transition-colors',
                  stickySearchTarget ? '' : 'opacity-90',
                ]"
                @click="handleSearchClick"
              >
                {{ stickyBar.searchLabel }}
              </button>
            </div>
          </div>

          <a
            v-if="whatsappUrl"
            :href="whatsappUrl"
            target="_blank"
            rel="noreferrer"
            class="flex items-center gap-2 bg-[#25D366]/10 text-[#25D366] px-4 py-2 rounded-xl font-bold hover:bg-[#25D366]/20 transition-colors text-sm shrink-0"
          >
            <MessageCircle class="w-4 h-4" />
            {{ stickyBar.whatsappLabel }}
          </a>
        </div>
      </div>
    </div>
  </Transition>

  <Transition name="sticky-bottom">
    <div v-if="isVisible" class="fixed bottom-0 left-0 w-full z-50 md:hidden">
      <div
        class="bg-white/90 backdrop-blur-xl border-t border-slate-200 shadow-[0_-8px_30px_rgb(0,0,0,0.1)] px-4 py-3 flex gap-2"
        style="padding-bottom: calc(12px + env(safe-area-inset-bottom))"
      >
        <button
          type="button"
          class="flex-1 bg-slate-900 text-white py-3.5 rounded-xl font-bold flex justify-center items-center gap-2 shadow-lg hover:bg-slate-800"
          @click="handleSearchClick"
        >
          <Search class="w-4 h-4" />
          {{ stickyBar.mobileSearchLabel }}
        </button>
        <a
          v-if="mobileWhatsappUrl"
          :href="mobileWhatsappUrl"
          target="_blank"
          rel="noreferrer"
          class="flex-1 bg-[#25D366] text-white py-3.5 rounded-xl font-bold flex justify-center items-center gap-2 shadow-lg hover:bg-[#20bd5a]"
        >
          <MessageCircle class="w-4 h-4" />
          {{ stickyBar.mobileWhatsappLabel }}
        </a>
      </div>
    </div>
  </Transition>
</template>

<style scoped>
.sticky-top-enter-active,
.sticky-top-leave-active,
.sticky-bottom-enter-active,
.sticky-bottom-leave-active {
  transition:
    transform 0.25s ease,
    opacity 0.25s ease;
}

.sticky-top-enter-from,
.sticky-top-leave-to {
  opacity: 0;
  transform: translateY(-100px);
}

.sticky-top-enter-to,
.sticky-top-leave-from {
  opacity: 1;
  transform: translateY(0);
}

.sticky-bottom-enter-from,
.sticky-bottom-leave-to {
  opacity: 0;
  transform: translateY(100px);
}

.sticky-bottom-enter-to,
.sticky-bottom-leave-from {
  opacity: 1;
  transform: translateY(0);
}
</style>
