import { useAsyncData } from '#imports'
import { computed } from 'vue'
import { usePublicLocale } from '~/composables/usePublicLocale'
import { loadExtrasLocaleExport } from '~/content/extras-export'
import { useResolvedPage } from '~/content/pages'
import { buildResolvedPageSeo, sortByOrder } from '~/content/utils'
import { normalizePublicLocale } from '~/utils/public-locales'
import { normalizePublicInternalPath } from '~/utils/public-routes'

const protectionVisuals = {
  'shield-alert': {
    color: 'text-slate-500',
    bgColor: 'bg-slate-100',
  },
  shield: {
    color: 'text-brand-orange',
    bgColor: 'bg-brand-orange/10',
  },
  'shield-check': {
    color: 'text-emerald-600',
    bgColor: 'bg-emerald-50',
  },
}

function formatExtraPrice(extra, ui) {
  if (!extra) {
    return {
      price: '',
      period: null,
    }
  }

  if (extra.pricingType === 'included') {
    return {
      price: ui?.insuranceIncludedLabel || 'Included',
      period: null,
    }
  }

  if (typeof extra.price === 'number' || typeof extra.price === 'string') {
    return {
      price: `$${extra.price}`,
      period: ui?.insurancePerDaySuffix || '/ day',
    }
  }

  return {
    price: '',
    period: null,
  }
}

export function buildServicesPageSeo(page, origin = '') {
  return buildResolvedPageSeo(page, origin, {
    ogImage: page?.heroImage || page?.featuredImage || '',
  })
}

export function useServicesContent() {
  const { locale } = usePublicLocale()
  const servicesContentPage = useResolvedPage('services')
  const { data: extrasData } = useAsyncData(
    () => `services-extras:${normalizePublicLocale(locale.value)}`,
    () => loadExtrasLocaleExport(locale.value),
    {
      watch: [locale],
      default: () => [],
    },
  )
  const structuredContent = computed(() => servicesContentPage.value?.structuredContent || {})
  const ui = computed(() => structuredContent.value.ui || {})
  const chauffeur = computed(() => structuredContent.value.chauffeur || {})
  const transfers = computed(() => structuredContent.value.transfers || {})
  const insurance = computed(() => structuredContent.value.insurance || {})
  const extrasByCode = computed(() => new Map(
    (Array.isArray(extrasData.value) ? extrasData.value : []).map((item) => [String(item?.code || item?.id || ''), item]),
  ))

  const servicesHero = computed(() => ({
    badge: servicesContentPage.value?.subtitle || '',
    title: servicesContentPage.value?.title || '',
    description: servicesContentPage.value?.excerpt || '',
    image: structuredContent.value.heroImage
      || servicesContentPage.value?.heroImage
      || servicesContentPage.value?.featuredImage
      || '',
    imageAlt: servicesContentPage.value?.heroImageAlt
      || servicesContentPage.value?.cardImageAlt
      || servicesContentPage.value?.title
      || '',
  }))

  const chauffeurContent = computed(() => ({
    label: chauffeur.value.label || '',
    title: chauffeur.value.title || '',
    highlight: chauffeur.value.highlight || '',
    description: chauffeur.value.description || '',
    features: Array.isArray(chauffeur.value.features) ? chauffeur.value.features : [],
    image: chauffeur.value.image || servicesHero.value.image,
    imageAlt: chauffeur.value.imageAlt || chauffeur.value.label || servicesContentPage.value?.title || '',
    ctaLabel: chauffeur.value.ctaLabel || '',
    ctaUrl: normalizePublicInternalPath(chauffeur.value.ctaUrl, locale.value),
  }))

  const chauffeurSocialProofCard = computed(() => ({
    title: ui.value.chauffeurBadgeTitle || '',
    subtitle: ui.value.chauffeurBadgeMeta || '',
    text: ui.value.chauffeurBadgeDescription || '',
  }))

  const transfersContent = computed(() => ({
    label: transfers.value.label || '',
    title: transfers.value.title || '',
    highlight: transfers.value.highlight || '',
    description: transfers.value.description || '',
    ctaLabel: transfers.value.ctaLabel || '',
    ctaUrl: normalizePublicInternalPath(transfers.value.ctaUrl, locale.value),
    modeLabel: ui.value.transfersModeLabel || '',
    modeValue: ui.value.transfersModeValue || '',
  }))

  const transferRoutes = computed(() => sortByOrder(transfers.value.routes || []).map((route) => ({
    route: route.route || '',
    note: route.note || '',
    modeValue: route.modeValue || transfersContent.value.modeValue,
  })))

  const insuranceContent = computed(() => ({
    label: insurance.value.label || '',
    title: insurance.value.title || '',
    highlight: insurance.value.highlight || '',
    description: insurance.value.description || '',
    ctaLabel: insurance.value.ctaLabel || '',
    ctaUrl: normalizePublicInternalPath(insurance.value.ctaUrl, locale.value),
    popularLabel: ui.value.insurancePopularLabel || '',
    noteTitle: ui.value.insuranceNoteTitle || '',
    extraNote: ui.value.insuranceExtraNote || '',
  }))

  const insurancePlans = computed(() => sortByOrder(structuredContent.value.protectionPlans || []).map((plan) => {
    const key = String(plan?.key || '')
    const extra = key ? extrasByCode.value.get(key) : null
    const pricePresentation = extra ? formatExtraPrice(extra, ui.value) : {
      price: plan?.priceLabel || '',
      period: plan?.period || null,
    }

    return {
      ...plan,
      name: extra?.name || plan?.name || '',
      description: plan?.description || extra?.description || '',
      features: Array.isArray(plan?.features) ? plan.features : [],
      price: pricePresentation.price,
      period: pricePresentation.period,
      popular: Boolean(plan?.isPopular),
      ...(protectionVisuals[plan?.iconKey] || protectionVisuals['shield-alert']),
    }
  }))

  const insuranceNote = computed(() => structuredContent.value.insuranceNote || '')

  return {
    servicesContentPage,
    servicesHero,
    chauffeurContent,
    chauffeurSocialProofCard,
    transfersContent,
    transferRoutes,
    insuranceContent,
    insurancePlans,
    insuranceNote,
  }
}
