<script setup>
import { motion } from 'motion-v'
import {
  Car,
  Check,
  ChevronLeft,
  ChevronRight,
  Eye,
  Flame,
  Scale,
  Star,
  TrendingUp,
  Zap,
} from 'lucide-vue-next'
import { differenceInDays } from 'date-fns'
import { formatPublicDayCount, formatPublicMoney } from '~/content/utils'
import { useSearchContent } from '~/content/search'
const { locale } = usePublicLocale()

const searchContent = useSearchContent()
const searchUi = computed(() => searchContent.searchUi.value)

const props = defineProps({
  car: {
    type: Object,
    required: true,
  },
  index: {
    type: Number,
    default: 0,
  },
  isComparing: {
    type: Boolean,
    default: false,
  },
  dateRange: {
    type: Object,
    default: () => ({ from: null, to: null }),
  },
  canBook: {
    type: Boolean,
    default: true,
  },
})

const emit = defineEmits(['compare', 'book'])

const currentImage = ref(0)
const currencyCode = computed(() => String(props.car.currency || 'USD').toUpperCase())

const rentalDays = computed(() => {
  const from = props.dateRange?.from
  const to = props.dateRange?.to

  if (!from || !to) {
    return 0
  }

  const days = differenceInDays(to, from)
  return days > 0 ? days : 1
})

const totalPrice = computed(() => props.car.price * (rentalDays.value || 1))
const priceLabel = computed(() => formatPublicMoney(props.car.price, currencyCode.value, locale.value))
const totalPriceLabel = computed(() => formatPublicMoney(totalPrice.value, currencyCode.value, locale.value))
const oldPriceLabel = computed(() => formatPublicMoney(props.car.oldPrice, currencyCode.value, locale.value))
const hasDiscount = computed(() => Number(props.car.oldPrice || 0) > Number(props.car.price || 0))
const discountPercent = computed(() => {
  const oldPrice = Number(props.car.oldPrice || 0)
  const price = Number(props.car.price || 0)

  if (!oldPrice || !price || oldPrice <= price) {
    return null
  }

  return Math.max(1, Math.round(((oldPrice - price) / oldPrice) * 100))
})
const ratingLabel = computed(() => {
  const rating = Number(props.car.rating)

  return Number.isFinite(rating) && rating > 0
    ? rating.toFixed(1)
    : (props.car.ratingFallbackLabel || searchUi.value.ratingNewLabel)
})
const hasImages = computed(() => props.car.images.length > 0)
const totalDurationLabel = computed(() => {
  if (rentalDays.value <= 0) {
    return ''
  }

  return formatPublicDayCount(rentalDays.value, locale.value, 'search.totalForTemplate')
})

function nextImage(event) {
  if (!hasImages.value) {
    return
  }

  event.preventDefault()
  event.stopPropagation()
  currentImage.value = (currentImage.value + 1) % props.car.images.length
}

function prevImage(event) {
  if (!hasImages.value) {
    return
  }

  event.preventDefault()
  event.stopPropagation()
  currentImage.value = (currentImage.value - 1 + props.car.images.length) % props.car.images.length
}
</script>

<template>
  <motion.div
    layout
    :initial="{ opacity: 0, scale: 0.9, y: 20 }"
    :animate="{ opacity: 1, scale: 1, y: 0 }"
    :exit="{ opacity: 0, scale: 0.9, y: 20 }"
    :transition="{ duration: 0.3, delay: index * 0.05 }"
    :class="[
      'bg-white rounded-2xl overflow-hidden border transition-all duration-300 group flex flex-col hover:shadow-xl hover:shadow-slate-200/40',
      isComparing ? 'border-brand-orange ring-1 ring-brand-orange' : 'border-white/60',
    ]"
  >
    <div class="relative aspect-[4/3] overflow-hidden bg-slate-100 group/gallery">
      <img
        v-if="hasImages"
        :src="car.images[currentImage]"
        :alt="`${car.brand} ${car.model}`"
        class="w-full h-full object-cover transition-transform duration-700 group-hover/gallery:scale-105"
      >
      <div v-else class="absolute inset-0 flex flex-col items-center justify-center gap-3 bg-slate-100 text-slate-400">
        <Car class="w-10 h-10" />
        <span class="text-[11px] font-bold uppercase tracking-[0.24em]">{{ searchUi.imageComingSoonLabel }}</span>
      </div>

      <div class="absolute inset-x-0 bottom-0 h-24 bg-gradient-to-t from-black/40 to-transparent pointer-events-none" />
      <div class="absolute inset-x-0 top-0 h-24 bg-gradient-to-b from-black/20 to-transparent pointer-events-none" />

      <template v-if="car.images.length > 1">
        <button
          type="button"
          class="absolute left-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-full bg-white/90 backdrop-blur-sm flex items-center justify-center text-slate-700 opacity-0 group-hover/gallery:opacity-100 transition-all hover:bg-white hover:scale-105 z-20 shadow-sm"
          @click="prevImage"
        >
          <ChevronLeft class="w-4 h-4" />
        </button>

        <button
          type="button"
          class="absolute right-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-full bg-white/90 backdrop-blur-sm flex items-center justify-center text-slate-700 opacity-0 group-hover/gallery:opacity-100 transition-all hover:bg-white hover:scale-105 z-20 shadow-sm"
          @click="nextImage"
        >
          <ChevronRight class="w-4 h-4" />
        </button>

        <div class="absolute bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-1.5 z-20">
          <div
            v-for="(image, imageIndex) in car.images"
            :key="`${image}-${imageIndex}`"
            :class="[
              'transition-all duration-300 rounded-full',
              imageIndex === currentImage ? 'w-4 h-1.5 bg-white' : 'w-1.5 h-1.5 bg-white/50 hover:bg-white/80',
            ]"
          />
        </div>
      </template>

      <div class="absolute top-4 left-4 flex flex-col items-start gap-2 z-20 pointer-events-none">
        <div
          v-if="car.marketingBadge"
          class="bg-slate-900 text-white text-[10px] font-bold uppercase tracking-widest px-3 py-1.5 rounded-full shadow-lg"
        >
          {{ car.marketingBadge }}
        </div>

        <div
          v-if="car.isNewArrival"
          class="bg-white text-slate-900 text-[10px] font-bold uppercase tracking-widest px-3 py-1.5 rounded-full shadow-lg"
        >
          {{ searchUi.newArrivalBadgeLabel }}
        </div>

        <div
          v-if="car.hotDeal"
          class="bg-brand-orange text-white text-[10px] font-bold uppercase tracking-widest px-3 py-1.5 rounded-full shadow-lg flex items-center gap-1.5"
        >
          <Zap class="w-3 h-3" fill="currentColor" /> {{ searchUi.hotDealBadgeLabel }}
        </div>
      </div>

      <button
        type="button"
        :class="[
          'absolute top-4 right-4 z-20 w-9 h-9 rounded-full shadow-lg flex items-center justify-center transition-all duration-300 hover:scale-110',
          isComparing ? 'bg-slate-900 text-white' : 'bg-white text-slate-600 hover:text-slate-900',
        ]"
        :title="isComparing ? searchUi.compareActionRemoveLabel : searchUi.compareActionAddLabel"
        @click="$emit('compare', car)"
      >
        <Scale class="w-4 h-4" />
      </button>
    </div>

    <div class="p-5 flex-1 flex flex-col relative bg-white">
      <div class="flex items-start justify-between mb-2">
        <div class="min-w-0 pr-4">
          <div class="text-[11px] font-semibold text-slate-500 uppercase tracking-widest mb-1 truncate">
            {{ car.brand }}
          </div>
          <h3 class="text-xl font-display font-bold text-slate-900 leading-tight truncate">
            {{ car.model }}
          </h3>
        </div>
        <div class="flex items-center gap-1 text-slate-700 shrink-0 mt-1 bg-slate-50 px-2 py-1 rounded-lg">
          <Star class="w-3.5 h-3.5 fill-current text-brand-orange" />
          <span class="text-sm font-bold">{{ ratingLabel }}</span>
        </div>
      </div>

      <div
        v-if="car.deliveryTag"
        class="inline-flex items-center gap-1.5 text-[10px] font-bold text-emerald-700 bg-emerald-50 px-2.5 py-1.5 rounded-md mb-3 w-fit border border-emerald-100"
      >
        <Check class="w-3 h-3" /> {{ car.deliveryTag }}
      </div>

      <div class="flex flex-wrap gap-2 mb-5">
        <div
          v-if="car.scarcity"
          class="inline-flex items-center gap-1.5 text-[10px] font-bold text-brand-orange bg-brand-orange/10 px-2.5 py-1.5 rounded-md"
        >
          <Flame class="w-3 h-3" /> {{ car.scarcity }}
        </div>

        <div
          v-if="car.viewers"
          class="inline-flex items-center gap-1.5 text-[10px] font-medium text-slate-600 bg-white/50 backdrop-blur-md px-2.5 py-1.5 rounded-md border border-white/60 shadow-sm"
        >
          <Eye class="w-3 h-3 text-slate-400" />
          <span><strong class="text-slate-900">{{ car.viewers }}</strong> {{ searchUi.viewing }}</span>
        </div>

        <div
          v-if="car.bookedToday > 0"
          class="inline-flex items-center gap-1.5 text-[10px] font-medium text-slate-600 bg-slate-50 px-2.5 py-1.5 rounded-md border border-slate-100"
        >
          <TrendingUp class="w-3 h-3 text-slate-400" />
          <span>{{ searchUi.bookedToday.replace('{count}', String(car.bookedToday)).replace('{suffix}', car.bookedToday === 1 ? '' : 's') }}</span>
        </div>
      </div>

      <div class="flex flex-wrap gap-x-3 gap-y-1 mb-6 mt-auto">
        <template v-for="(feature, featureIndex) in car.features.slice(0, 3)" :key="feature">
          <div class="flex items-center gap-1.5">
            <span class="text-xs font-medium text-slate-600">{{ feature }}</span>
            <span
              v-if="featureIndex < Math.min(car.features.length, 3) - 1"
              class="w-1 h-1 rounded-full bg-slate-300"
            />
          </div>
        </template>
      </div>

      <div class="pt-4 border-t border-white/40 flex flex-col gap-3">
        <div class="min-w-0 rounded-2xl bg-slate-50/70 px-4 py-3 border border-slate-100/80">
          <div class="flex items-end flex-wrap gap-x-2 gap-y-1">
            <span class="text-[1.65rem] md:text-[1.9rem] font-bold text-slate-900 tracking-tight leading-none">{{ priceLabel }}</span>
            <span class="text-[10px] md:text-[11px] font-semibold text-slate-500 uppercase tracking-[0.18em] leading-none whitespace-nowrap pb-0.5">{{ searchUi.pricePerDaySuffix }}</span>
          </div>

          <div v-if="rentalDays > 0" class="mt-2 flex flex-wrap items-baseline gap-x-2 gap-y-1 text-[11px] md:text-xs leading-tight">
            <span class="uppercase tracking-[0.18em] text-slate-400 font-semibold">{{ searchUi.totalLabel }}</span>
            <span class="font-semibold text-slate-700">{{ totalPriceLabel }}</span>
            <span class="text-slate-400">{{ totalDurationLabel }}</span>
          </div>

          <div v-if="hasDiscount" class="mt-2 flex flex-wrap items-center gap-2">
            <span class="text-[11px] font-medium text-slate-400 line-through decoration-slate-300">{{ oldPriceLabel }}</span>
            <span class="text-[9px] font-bold text-brand-orange bg-brand-orange/10 px-1.5 py-0.5 rounded leading-none">
              -{{ discountPercent }}%
            </span>
          </div>
        </div>

        <button
          type="button"
          :disabled="!car.available || !canBook"
          class="w-full px-5 py-3 rounded-full text-[14px] sm:text-[15px] font-semibold leading-none text-center whitespace-nowrap transition-all duration-300 bg-brand-orange text-white hover:bg-[#E66000] hover:-translate-y-0.5 shadow-lg shadow-brand-orange/15 disabled:pointer-events-none"
          @click="$emit('book', car)"
        >
          {{ car.available && canBook ? searchUi.bookLabel : searchUi.unavailableLabel }}
        </button>
      </div>
    </div>
  </motion.div>
</template>
