<script setup>
import { AnimatePresence, motion } from 'motion-v';
import {
  Calendar,
  CheckCircle2,
  Building,
  MapPin,
  MessageCircle,
  Plane,
  Search,
} from "lucide-vue-next";
import { format } from 'date-fns';
import { formatPublicMoney } from "~/content/utils";
import AppCalendar from '~/components/shared/AppCalendar.vue';
import {
  normalizeCityRentalHref,
} from "~/components/city-rental/link-utils";
import { buildRentSearchRoute, buildRentTripQuery } from '~/utils/public-routes';

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

const { locale } = usePublicLocale();
const ui = usePublicUi();
const { locations, loadLocations } = usePublicSiteLocations();
const { baseDay, buildDate } = usePublicDateDefaults();
const heroSearchFormUi = computed(() => ui.value?.home?.searchForm || {});
const heroTopOffersUi = computed(() => ui.value?.home?.topOffers || {});

const hero = computed(() => props.hero || {});
const fallbackSearchUrl = computed(() => normalizeCityRentalHref(hero.value?.search?.ctaUrl));
const mobileWhatsappUrl = computed(() =>
  normalizeCityRentalHref(hero.value?.mobileWhatsappUrl || hero.value?.sideBoxCtaUrl),
);
const sideBoxCtaUrl = computed(() =>
  normalizeCityRentalHref(hero.value?.sideBoxCtaUrl || hero.value?.mobileWhatsappUrl),
);
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 priceChips = computed(() =>
  Array.isArray(props.hero?.priceChips) ? props.hero.priceChips : [],
);
const trustChips = computed(() =>
  Array.isArray(props.hero?.trustChips) ? props.hero.trustChips : [],
);

const pickupValueLabel = computed(() => {
  return pickupLocation.value?.name || hero.value?.search?.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 hero.value?.search?.datesValue || '';
});

function mergeDateAndTime(date, time) {
  if (!date || !time) {
    return null;
  }

  const nextDate = new Date(date);
  const [hours, minutes] = String(time).split(':').map((value) => Number(value));
  nextDate.setHours(hours || 0, minutes || 0, 0, 0);
  return nextDate.toISOString();
}

const searchTarget = computed(() => {
  if (!pickupLocation.value?.backendId || !searchDateRange.value?.from || !searchDateRange.value?.to) {
    return fallbackSearchUrl.value;
  }

  return buildRentSearchRoute(buildRentTripQuery({
    pickupLocationId: pickupLocation.value.backendId,
    dropoffLocationId: pickupLocation.value.backendId,
    pickupAt: mergeDateAndTime(searchDateRange.value.from, '12:30'),
    dropoffAt: mergeDateAndTime(searchDateRange.value.to, '08:30'),
    returnToSameLocation: '1',
  }), {
    locale: locale.value,
  });
});

function resolveInitialPickupLocation() {
  const targetName = String(hero.value?.search?.pickupValue || '').trim().toLowerCase();

  if (targetName) {
    const byName = locations.value.find((location) => String(location.name || '').trim().toLowerCase() === targetName);

    if (byName) {
      return byName;
    }
  }

  const downtownOffice = locations.value.find((location) => {
    const value = `${location?.name || ''} ${location?.city || ''} ${location?.code || ''} ${location?.rawCode || ''}`.toLowerCase();
    return value.includes('tbilisi') && value.includes('downtown') && value.includes('office');
  });

  const downtown = locations.value.find((location) => {
    const value = `${location?.name || ''} ${location?.city || ''} ${location?.code || ''} ${location?.rawCode || ''}`.toLowerCase();
    return value.includes('downtown') && (value.includes('tbilisi') || location?.type === 'office');
  });

  const office = locations.value.find((location) => {
    const value = `${location?.name || ''} ${location?.city || ''} ${location?.code || ''} ${location?.rawCode || ''}`.toLowerCase();
    return location?.type === 'office' && value.includes('tbilisi');
  });

  const tbilisi = locations.value.find((location) => {
    const value = `${location?.name || ''} ${location?.city || ''}`.toLowerCase();
    return value.includes('tbilisi') || value.includes('თბილისი');
  });

  return downtownOffice || downtown || office || tbilisi || locations.value.find((location) => location.type === 'airport') || locations.value[0] || null;
}

function syncPickupLocation() {
  if (!locations.value.length) {
    return;
  }

  if (pickupLocation.value) {
    const nextLocation = locations.value.find((location) => location.id === pickupLocation.value.id);

    if (nextLocation) {
      pickupLocation.value = nextLocation;
      return;
    }
  }

  pickupLocation.value = resolveInitialPickupLocation();
}

function togglePopover(popover) {
  activePopover.value = activePopover.value === popover ? null : popover;
}

function handleClickOutside(event) {
  if (!activePopover.value) {
    return;
  }

  const target = event.target;

  if (target instanceof Element && target.closest('[data-hero-popover-scope]')) {
    return;
  }

  activePopover.value = null;
}

watch(
  locations,
  () => {
    syncPickupLocation();
  },
  { immediate: true },
);

onMounted(async () => {
  activePopover.value = null
  document.addEventListener('pointerdown', handleClickOutside);
  await loadLocations();
  syncPickupLocation();
});

onBeforeUnmount(() => {
  document.removeEventListener('pointerdown', handleClickOutside);
});
</script>

<template>
  <section class="relative z-30 pt-24 pb-12 lg:pt-40 lg:pb-24 overflow-visible">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 relative z-10">
      <div class="flex flex-col lg:flex-row gap-8 lg:gap-12 items-center">
        <div class="flex-1 w-full max-w-3xl">
          <div
            class="hidden sm:flex items-center gap-2 text-sm font-medium text-brand-orange mb-6 bg-brand-orange/10 w-max px-3 py-1.5 rounded-full"
          >
            <MapPin class="w-4 h-4" />
            <span>{{ hero.eyebrow }}</span>
          </div>

          <h1
            class="text-4xl sm:text-5xl lg:text-5xl xl:text-6xl font-display font-bold text-slate-900 leading-[1.1] mb-5 sm:mb-6 tracking-tight"
          >
            {{ hero.title }}
          </h1>

          <p
            class="text-base sm:text-lg lg:text-xl text-slate-600 leading-relaxed mb-6 sm:mb-8 max-w-2xl"
          >
            {{ hero.description }}
          </p>

          <div class="flex items-center gap-3 sm:gap-4 mb-8">
            <div
              v-for="chip in priceChips"
              :key="chip.label"
              class="bg-white px-3 sm:px-4 py-2 rounded-xl sm:rounded-2xl shadow-sm border border-slate-100 flex-1 sm:flex-none"
            >
              <div
                class="text-[9px] sm:text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-0.5 sm:mb-1"
              >
                {{ chip.label }}
              </div>
              <div class="text-slate-900 font-bold">
                {{ heroTopOffersUi.fromLabel }}
                <span class="text-base sm:text-lg">{{
                  formatPublicMoney(chip.amount, chip.currency, locale.value, {
                    forceFraction: false,
                  })
                }}</span
                ><span class="text-xs sm:text-sm text-slate-500 font-normal">{{
                  chip.suffix
                }}</span>
              </div>
            </div>
          </div>

          <div
            id="city-rental-search"
            class="bg-white/80 backdrop-blur-xl border border-white p-2 sm:p-3 rounded-3xl shadow-[0_8px_30px_rgb(0,0,0,0.04)] mb-8 w-full"
          >
            <div class="relative flex flex-col sm:flex-row gap-2">
              <div
                class="flex-1 flex flex-col sm:flex-row bg-slate-50/50 rounded-2xl p-1 gap-1 border border-slate-100/50"
                data-hero-popover-scope
              >
                <div
                  class="flex-1 px-4 py-3 sm:py-3 cursor-pointer bg-white sm:bg-transparent shadow-sm sm:shadow-none hover:bg-white rounded-xl transition-all"
                  @click="togglePopover('pickup')"
                >
                  <div
                    class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1"
                  >
                    {{ hero.search.pickupLabel }}
                  </div>
                  <div class="flex items-center gap-2 text-slate-900 font-medium">
                    <MapPin class="w-4 h-4 text-brand-orange" />
                    <span class="truncate">{{ pickupValueLabel }}</span>
                  </div>
                </div>
                <div class="hidden sm:block w-[1px] bg-slate-200 my-2" />
                <div
                  class="flex-1 px-4 py-3 sm:py-3 cursor-pointer bg-white sm:bg-transparent shadow-sm sm:shadow-none hover:bg-white rounded-xl transition-all mt-1 sm:mt-0"
                  @click="togglePopover('dates')"
                >
                  <div
                    class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1"
                  >
                    {{ hero.search.datesLabel }}
                  </div>
                  <div class="flex items-center gap-2 text-slate-900 font-medium">
                    <Calendar class="w-4 h-4 text-brand-orange" />
                    <span class="truncate">{{ datesValueLabel }}</span>
                  </div>
                </div>
              </div>

              <NuxtLink
                v-if="searchTarget"
                :to="searchTarget"
                class="bg-slate-900 hover:bg-slate-800 text-white px-8 py-4 sm:py-0 rounded-2xl font-bold transition-all flex items-center justify-center gap-2 shrink-0 group mt-2 sm:mt-0 h-auto sm:h-auto"
              >
                <Search
                  class="w-5 h-5 text-brand-orange transition-transform group-hover:-rotate-[-10deg] group-hover:scale-110"
                />
                {{ hero.search.ctaLabel }}
              </NuxtLink>
            </div>

            <AnimatePresence>
              <motion.div
                v-if="activePopover === 'pickup'"
                :initial="{ opacity: 0, y: 10, scale: 0.98 }"
                :animate="{ opacity: 1, y: 0, scale: 1 }"
                :exit="{ opacity: 0, y: 10, scale: 0.98 }"
                :transition="{ duration: 0.2 }"
                data-hero-popover-scope
                class="absolute top-full left-0 w-full mt-4 bg-white rounded-[2rem] shadow-[0_20px_60px_rgb(0,0,0,0.08)] border border-slate-100 p-6 z-[60]"
              >
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                  <div>
                    <div class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-4 flex items-center gap-2">
                      <Plane class="w-3.5 h-3.5" /> {{ heroSearchFormUi.airportGroupLabel }}
                    </div>
                    <div class="space-y-2">
                      <button
                        v-for="location in locations.filter((item) => item.type === 'airport')"
                        :key="location.id"
                        type="button"
                        :class="[
                          'w-full flex items-center justify-between p-4 rounded-2xl transition-all text-left border',
                          pickupLocation?.id === location.id
                            ? 'bg-brand-orange/5 border-brand-orange/30 text-brand-orange'
                            : 'border-white/40 bg-white/40 text-slate-600 hover:bg-white/60 hover:border-white/60 hover:text-slate-900 shadow-sm',
                        ]"
                        @click="pickupLocation = location; activePopover = null"
                      >
                        <div>
                          <div class="font-semibold text-sm">{{ location.name }}</div>
                          <div class="text-xs opacity-70 mt-0.5">{{ location.city }}</div>
                        </div>
                        <div
                          :class="[
                            'text-xs font-bold px-2 py-1 rounded-lg',
                            pickupLocation?.id === location.id ? 'bg-brand-orange/10' : 'bg-slate-100',
                          ]"
                        >
                          {{ location.code }}
                        </div>
                      </button>
                    </div>
                  </div>

                  <div>
                    <div class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-4 flex items-center gap-2">
                      <Building class="w-3.5 h-3.5" /> {{ heroSearchFormUi.cityGroupLabel }}
                    </div>
                    <div class="space-y-2">
                      <button
                        v-for="location in locations.filter((item) => item.type === 'city')"
                        :key="location.id"
                        type="button"
                        :class="[
                          'w-full flex items-center justify-between p-4 rounded-2xl transition-all text-left border',
                          pickupLocation?.id === location.id
                            ? 'bg-brand-orange/5 border-brand-orange/30 text-brand-orange'
                            : 'border-white/40 bg-white/40 text-slate-600 hover:bg-white/60 hover:border-white/60 hover:text-slate-900 shadow-sm',
                        ]"
                        @click="pickupLocation = location; activePopover = null"
                      >
                        <div>
                          <div class="font-semibold text-sm">{{ location.name }}</div>
                          <div class="text-xs opacity-70 mt-0.5">{{ location.city }}</div>
                        </div>
                        <div
                          :class="[
                            'text-xs font-bold px-2 py-1 rounded-lg',
                            pickupLocation?.id === location.id ? 'bg-brand-orange/10' : 'bg-slate-100',
                          ]"
                        >
                          {{ location.code }}
                        </div>
                      </button>
                    </div>
                  </div>
                </div>
              </motion.div>
            </AnimatePresence>

            <AnimatePresence>
              <motion.div
                v-if="activePopover === 'dates'"
                :initial="{ opacity: 0, y: 10, scale: 0.98 }"
                :animate="{ opacity: 1, y: 0, scale: 1 }"
                :exit="{ opacity: 0, y: 10, scale: 0.98 }"
                :transition="{ duration: 0.2 }"
                data-hero-popover-scope
                class="absolute top-full left-0 w-full mt-4 bg-white rounded-[2rem] shadow-[0_20px_60px_rgb(0,0,0,0.08)] border border-slate-100 p-6 z-[60] flex flex-col items-center"
              >
                <AppCalendar
                  mode="range"
                  :selected="searchDateRange"
                  :number-of-months="2"
                  :disabled="{ before: baseDay }"
                  class="font-sans"
                  @select="(range) => { searchDateRange = range; if (range?.from && range?.to) { activePopover = null } }"
                />
                <div class="w-full flex justify-end mt-4">
                  <button
                    type="button"
                    class="px-6 py-2 bg-slate-900 text-white rounded-xl text-sm font-bold hover:bg-brand-orange transition-colors shadow-lg shadow-slate-900/20"
                    @click="activePopover = null"
                  >
                    {{ heroSearchFormUi.calendarDoneLabel }}
                  </button>
                </div>
              </motion.div>
            </AnimatePresence>
          </div>

          <a
            v-if="mobileWhatsappUrl"
            :href="mobileWhatsappUrl"
            target="_blank"
            rel="noreferrer"
            class="w-full lg:hidden flex items-center justify-center gap-2 bg-[#25D366]/10 hover:bg-[#25D366]/20 text-[#25D366] px-6 py-4 rounded-xl font-bold transition-all mb-8 border border-[#25D366]/20"
          >
            <MessageCircle class="w-5 h-5" />
            {{ hero.mobileWhatsappLabel }}
          </a>

          <div
            class="grid grid-cols-2 sm:flex sm:flex-wrap items-center gap-x-4 gap-y-3"
          >
            <div
              v-for="feature in trustChips"
              :key="feature"
              class="flex items-center gap-2"
            >
              <CheckCircle2 class="w-4 h-4 text-brand-orange shrink-0" />
              <span
                class="text-[13px] sm:text-sm font-medium text-slate-700 leading-tight"
                >{{ feature }}</span
              >
            </div>
          </div>
        </div>

        <div
          class="hidden lg:flex lg:w-[320px] shrink-0 justify-end flex-col gap-4"
        >
          <a
            v-if="sideBoxCtaUrl"
            :href="sideBoxCtaUrl"
            target="_blank"
            rel="noreferrer"
            class="w-full flex items-center justify-center gap-2 bg-[#25D366] hover:bg-[#20bd5a] text-white px-6 py-5 rounded-2xl font-bold transition-all shadow-lg shadow-green-500/20 group"
          >
            <MessageCircle
              class="w-5 h-5 group-hover:scale-110 transition-transform"
            />
            {{ hero.sideBoxCta }}
          </a>
          <div
            class="bg-white/60 backdrop-blur-md rounded-2xl p-4 border border-white text-center"
          >
            <div class="text-sm font-semibold text-slate-900 mb-1">
              {{ hero.sideBoxTitle }}
            </div>
            <div class="text-xs text-slate-500">{{ hero.sideBoxText }}</div>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>
