import { computed } from 'vue'
import { buildPublicLocaleSwitchContext, useRegisterPublicLocaleSwitchContext } from '~/composables/usePublicLocaleSwitchContext'
import { usePublicLocale } from '~/composables/usePublicLocale'
import { useResolvedPage } from '~/content/pages'
import { buildResolvedPageSeo } from '~/content/utils'
import { resolvePublicUiValue } from '~/i18n/public-ui'
import { DEFAULT_PUBLIC_LOCALE } from '~/utils/public-locales'
import { normalizeImplementedPublicInternalPath, normalizePublicInternalPath } from '~/utils/public-routes'

function buildSearchPromoFallback(locale) {
  return {
    isMock: true,
    title: resolvePublicUiValue(locale, 'search.secretDealsTitle'),
    descriptionPrefix: resolvePublicUiValue(locale, 'search.secretDealsDescriptionPrefix'),
    accentLabel: resolvePublicUiValue(locale, 'search.secretDealsAccent'),
    descriptionSuffix: resolvePublicUiValue(locale, 'search.secretDealsDescriptionSuffix'),
    primaryLabel: resolvePublicUiValue(locale, 'search.signIn'),
    secondaryLabel: resolvePublicUiValue(locale, 'search.register'),
    primaryHref: null,
    secondaryHref: null,
  }
}

function buildSearchPromo(page, locale) {
  const fallback = buildSearchPromoFallback(locale)
  const promoContent = page?.structuredContent?.promo || page?.promo || null

  if (!promoContent) {
    return fallback
  }

  return {
    isMock: false,
    title: promoContent.title || fallback.title,
    descriptionPrefix: promoContent.descriptionPrefix || fallback.descriptionPrefix,
    accentLabel: promoContent.accentLabel || fallback.accentLabel,
    descriptionSuffix: promoContent.descriptionSuffix || fallback.descriptionSuffix,
    primaryLabel: promoContent.primaryLabel || fallback.primaryLabel,
    secondaryLabel: promoContent.secondaryLabel || fallback.secondaryLabel,
    primaryHref: normalizeImplementedPublicInternalPath(promoContent.primaryHref, locale),
    secondaryHref: normalizeImplementedPublicInternalPath(promoContent.secondaryHref, locale),
  }
}

function normalizeSearchUi(page, locale = DEFAULT_PUBLIC_LOCALE) {
  const ui = page?.structuredContent?.ui || {}

  return {
    headerTitle: ui.headerTitle || page?.title || '',
    searchPlaceholder: resolvePublicUiValue(locale, 'search.searchPlaceholder') || ui.searchPlaceholder || '',
    maxPriceLabel: resolvePublicUiValue(locale, 'search.maxPriceLabel') || ui.maxPriceLabel || '',
    sortByLabel: resolvePublicUiValue(locale, 'search.sortByLabel') || ui.sortByLabel || '',
    sortRecommendedLabel: resolvePublicUiValue(locale, 'search.sortRecommendedLabel') || ui.sortRecommendedLabel || '',
    sortPriceLowLabel: resolvePublicUiValue(locale, 'search.sortPriceLowLabel') || ui.sortPriceLowLabel || '',
    sortPriceHighLabel: resolvePublicUiValue(locale, 'search.sortPriceHighLabel') || ui.sortPriceHighLabel || '',
    sortRatingLabel: resolvePublicUiValue(locale, 'search.sortRatingLabel') || ui.sortRatingLabel || '',
    loadingLabel: ui.loadingLabel || resolvePublicUiValue(locale, 'search.loadingLabel') || '',
    resultsSingularLabel: resolvePublicUiValue(locale, 'search.compareVehicleSingular') || ui.resultsSingularLabel || '',
    resultsPluralLabel: resolvePublicUiValue(locale, 'search.compareVehiclePlural') || ui.resultsPluralLabel || '',
    defaultLocationLabel: resolvePublicUiValue(locale, 'search.defaultLocationLabel') || ui.defaultLocationLabel || '',
    dailyRateLabel: resolvePublicUiValue(locale, 'search.dailyRateLabel') || ui.dailyRateLabel || '',
    pricePerDaySuffix: resolvePublicUiValue(locale, 'search.pricePerDaySuffix') || ui.pricePerDaySuffix || '',
    imageComingSoonLabel: resolvePublicUiValue(locale, 'common.imageComingSoon') || ui.imageComingSoonLabel || '',
    daySingularLabel: resolvePublicUiValue(locale, 'common.day') || ui.daySingularLabel || '',
    dayPluralLabel: resolvePublicUiValue(locale, 'common.days') || ui.dayPluralLabel || '',
    totalLabel: resolvePublicUiValue(locale, 'common.total') || ui.totalLabel || '',
    totalForTemplate: resolvePublicUiValue(locale, 'search.totalForTemplate') || ui.totalForTemplate || '',
    bookLabel: resolvePublicUiValue(locale, 'search.bookLabel') || ui.bookLabel || '',
    unavailableLabel: resolvePublicUiValue(locale, 'search.unavailableLabel') || ui.unavailableLabel || '',
    continueLabel: resolvePublicUiValue(locale, 'search.continueLabel') || ui.continueLabel || '',
    catalogLoadFailedLabel: resolvePublicUiValue(locale, 'search.catalogLoadFailedLabel'),
    trustBannerRateLabel: ui.trustBannerRateLabel || '',
    trustBannerQuoteLabel: ui.trustBannerQuoteLabel || '',
    trustBannerSupportLabel: ui.trustBannerSupportLabel || '',
    compareLimitMessage: resolvePublicUiValue(locale, 'search.compareLimitMessage') || ui.compareLimitMessage || '',
    compareTitle: resolvePublicUiValue(locale, 'search.compareTitle') || ui.compareTitle || '',
    compareSelectedTemplate: ui.compareSelectedTemplate || resolvePublicUiValue(locale, 'search.compareSelectedTemplate'),
    compareClearAllLabel: resolvePublicUiValue(locale, 'search.compareClearAllLabel') || ui.compareClearAllLabel || '',
    compareNowLabel: resolvePublicUiValue(locale, 'search.compareNowLabel') || ui.compareNowLabel || '',
    compareAddVehicleLabel: resolvePublicUiValue(locale, 'search.compareAddVehicleLabel') || ui.compareAddVehicleLabel || '',
    compareActionAddLabel: resolvePublicUiValue(locale, 'search.compareActionAddLabel') || ui.compareActionAddLabel || '',
    compareActionRemoveLabel: resolvePublicUiValue(locale, 'search.compareActionRemoveLabel') || ui.compareActionRemoveLabel || '',
    newArrivalBadgeLabel: resolvePublicUiValue(locale, 'search.newArrivalBadgeLabel') || ui.newArrivalBadgeLabel || '',
    hotDealBadgeLabel: resolvePublicUiValue(locale, 'search.hotDealBadgeLabel') || ui.hotDealBadgeLabel || '',
    emptyTitle: ui.emptyTitle || '',
    emptyDescription: ui.emptyDescription || '',
    clearFiltersLabel: resolvePublicUiValue(locale, 'search.clearFiltersLabel') || ui.clearFiltersLabel || '',
    featuredLabel: resolvePublicUiValue(locale, 'search.featuredLabel'),
    luxuryBadgeLabel: resolvePublicUiValue(locale, 'search.luxuryBadgeLabel'),
    ratingNewLabel: resolvePublicUiValue(locale, 'search.ratingNewLabel'),
    soldOutSelectedDatesLabel: resolvePublicUiValue(locale, 'search.soldOutSelectedDatesLabel'),
    onlyOneLeftTemplate: resolvePublicUiValue(locale, 'search.onlyOneLeftTemplate'),
    onlyFewLeftTemplate: resolvePublicUiValue(locale, 'search.onlyFewLeftTemplate'),
    transferServiceLabel: resolvePublicUiValue(locale, 'search.transferServiceLabel'),
    oneWayAvailableLabel: resolvePublicUiValue(locale, 'search.oneWayAvailableLabel'),
    typeVehicleLabel: resolvePublicUiValue(locale, 'search.typeVehicleLabel'),
    typeEconomyLabel: resolvePublicUiValue(locale, 'search.typeEconomyLabel'),
    typeStandardLabel: resolvePublicUiValue(locale, 'search.typeStandardLabel'),
    typeSedanLabel: resolvePublicUiValue(locale, 'search.typeSedanLabel'),
    typeSuvLabel: resolvePublicUiValue(locale, 'search.typeSuvLabel'),
    typeVansLabel: resolvePublicUiValue(locale, 'search.typeVansLabel'),
    typeLuxuryLabel: resolvePublicUiValue(locale, 'search.typeLuxuryLabel'),
    allCategoryLabel: resolvePublicUiValue(locale, 'search.allCategoryLabel'),
    locationLabel: resolvePublicUiValue(locale, 'search.locationLabel'),
    datesLabel: resolvePublicUiValue(locale, 'search.datesLabel'),
    applyDatesLabel: resolvePublicUiValue(locale, 'search.applyDatesLabel'),
    pickupPlaceholderLabel: resolvePublicUiValue(locale, 'search.pickupPlaceholder'),
    dropoffPlaceholderLabel: resolvePublicUiValue(locale, 'search.dropoffPlaceholder'),
    brandLabel: resolvePublicUiValue(locale, 'search.brandLabel'),
    seatsLabel: resolvePublicUiValue(locale, 'search.seatsLabel'),
    transmissionLabel: resolvePublicUiValue(locale, 'search.transmissionLabel'),
    engineLabel: resolvePublicUiValue(locale, 'search.engineLabel'),
    featuresLabel: resolvePublicUiValue(locale, 'search.featuresLabel'),
    conditionsLabel: resolvePublicUiValue(locale, 'search.conditionsLabel'),
    resultsFoundLabel: resolvePublicUiValue(locale, 'search.resultsFoundLabel'),
    compareYearLabel: resolvePublicUiValue(locale, 'search.compareYearLabel'),
    compareTypeLabel: resolvePublicUiValue(locale, 'search.compareTypeLabel'),
    compareSeatsLabel: resolvePublicUiValue(locale, 'search.compareSeatsLabel'),
    compareTransmissionLabel: resolvePublicUiValue(locale, 'search.compareTransmissionLabel'),
    compareEngineLabel: resolvePublicUiValue(locale, 'search.compareEngineLabel'),
    compareFeaturesLabel: resolvePublicUiValue(locale, 'search.compareFeaturesLabel'),
    compareOptionsLabel: resolvePublicUiValue(locale, 'search.compareOptionsLabel'),
    compareBrowseLabel: resolvePublicUiValue(locale, 'search.compareBrowseLabel'),
    compareAddDescription: resolvePublicUiValue(locale, 'search.compareAddDescription'),
    viewing: resolvePublicUiValue(locale, 'search.viewing'),
    bookedToday: resolvePublicUiValue(locale, 'search.bookedToday'),
  }
}

function buildSearchSortOptions(ui) {
  return [
    { value: 'recommended', label: ui.sortRecommendedLabel },
    { value: 'price-low', label: ui.sortPriceLowLabel },
    { value: 'price-high', label: ui.sortPriceHighLabel },
    { value: 'rating', label: ui.sortRatingLabel },
  ].filter((option) => option.label)
}

function formatSearchResultsLabelWithUi(count, ui, locale = DEFAULT_PUBLIC_LOCALE) {
  const singular = ui.resultsSingularLabel || resolvePublicUiValue(locale, 'search.compareVehicleSingular')
  const plural = ui.resultsPluralLabel || resolvePublicUiValue(locale, 'search.compareVehiclePlural')

  return `${count} ${count === 1 ? singular : plural}`
}

function formatSearchCompareSelectedLabelWithUi(count, max, ui, locale = DEFAULT_PUBLIC_LOCALE) {
  return String(ui.compareSelectedTemplate || resolvePublicUiValue(locale, 'search.compareSelectedTemplate'))
    .replace('{count}', String(count))
    .replace('{max}', String(max))
}

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

export function useSearchContent() {
  const { locale } = usePublicLocale()
  const searchPage = useResolvedPage('rent')
  const localeSwitchContext = computed(() => buildPublicLocaleSwitchContext(searchPage.value, { kind: 'list' }))

  useRegisterPublicLocaleSwitchContext(localeSwitchContext)

  const searchUi = computed(() => normalizeSearchUi(searchPage.value, locale.value))
  const searchSortOptions = computed(() => buildSearchSortOptions(searchUi.value))
  const searchPromo = computed(() => buildSearchPromo(searchPage.value, locale.value))

  function formatSearchResultsLabel(count) {
    return `${formatSearchResultsLabelWithUi(count, searchUi.value, locale.value)} ${searchUi.value.resultsFoundLabel}`.trim()
  }

  function formatSearchCompareSelectedLabel(count, max = 3) {
    return formatSearchCompareSelectedLabelWithUi(count, max, searchUi.value, locale.value)
  }

  return {
    searchPage,
    searchUi,
    searchSortOptions,
    searchPromo,
    formatSearchResultsLabel,
    formatSearchCompareSelectedLabel,
  }
}
