import { computed, unref } from 'vue'
import { buildPublicLocaleSwitchContext, useRegisterPublicLocaleSwitchContext } from '~/composables/usePublicLocaleSwitchContext'
import { useHomeContent } from '~/content/home'
import { useResolvedPage } from '~/content/pages'
import { PUBLIC_LOCALES } from '~/utils/public-locales'
import { buildRequestRoute } from '~/utils/public-routes'

function buildRequestFlowSeo(page, overrides = {}) {
  const seo = page?.seo || {}
  const isPrivateFlow = overrides.privateFlow === true
  const title = overrides.title || seo.title || page?.title || ''
  const description = overrides.description || seo.description || page?.excerpt || ''
  const ogImage = overrides.ogImage || seo.ogImage || page?.heroImage || page?.featuredImage || ''

  return {
    title,
    description,
    ogTitle: title,
    ogDescription: description,
    ogImage,
    robots: isPrivateFlow ? 'noindex,nofollow' : (seo.robots || 'noindex,nofollow'),
    canonical: isPrivateFlow ? null : (seo.canonical || null),
    hreflang: isPrivateFlow ? [] : (Array.isArray(seo.hreflang) ? seo.hreflang : []),
    xDefault: isPrivateFlow ? null : (seo.xDefault || null),
  }
}

function buildPathsByLocale(resolvePath) {
  return Object.fromEntries(
    PUBLIC_LOCALES
      .map((entry) => [entry.locale, resolvePath(entry.locale)])
      .filter(([, path]) => typeof path === 'string' && path.trim() !== ''),
  )
}

export function buildRequestPageSeo(page, options = {}) {
  return buildRequestFlowSeo(page, options)
}

export function useRequestContent(tokenRef = '') {
  const requestPage = useResolvedPage('request')
  const { homeHeroRequestForm } = useHomeContent()
  const requestToken = computed(() => String(unref(tokenRef) || '').trim())
  const ui = computed(() => requestPage.value?.structuredContent?.ui || {})

  const localeSwitchContext = computed(() => {
    if (!requestToken.value) {
      return buildPublicLocaleSwitchContext(requestPage.value, {
        kind: 'list',
      })
    }

    return buildPublicLocaleSwitchContext(requestPage.value, {
      kind: 'detail',
      sectionPath: '/request',
      detailLocales: PUBLIC_LOCALES.map((entry) => entry.locale),
      pathsByLocale: buildPathsByLocale((entryLocale) => buildRequestRoute(requestToken.value, {}, {
        locale: entryLocale,
      }).path),
    })
  })

  useRegisterPublicLocaleSwitchContext(localeSwitchContext)

  const requestBudgetTierLabels = computed(() => (homeHeroRequestForm.value?.budgetOptions || []).reduce((labels, option) => {
    if (option.tier && option.label) {
      labels[option.tier] = option.label
    }

    return labels
  }, {}))

  const requestTrackerUi = computed(() => ({
    statusEyebrow: ui.value.statusEyebrow || '',
    missingTokenLabel: ui.value.missingTokenLabel || '',
    loadingLabel: ui.value.loadingLabel || '',
    processTimelineTitle: ui.value.processTimelineTitle || '',
    liveUpdatesTitle: ui.value.liveUpdatesTitle || '',
    systemWaitingLabel: ui.value.systemWaitingLabel || '',
    yourRequestLabel: ui.value.yourRequestLabel || '',
    offersTitle: ui.value.offersTitle || '',
    offersReadyLabel: ui.value.offersReadyLabel || '',
    agentWorkingLabel: ui.value.agentWorkingLabel || '',
    activeStepDescription: ui.value.activeStepDescription || '',
    pendingLabel: ui.value.pendingLabel || '',
    requestedVehicleLabel: ui.value.requestedVehicleLabel || '',
    customOfferLabel: ui.value.customOfferLabel || '',
    offerPublishedLabel: ui.value.offerPublishedLabel || '',
    openBookingLabel: ui.value.openBookingLabel || '',
    awaitingBookingLabel: ui.value.awaitingBookingLabel || '',
    loadErrorLabel: ui.value.loadErrorLabel || '',
    requestConnectedLabel: ui.value.requestConnectedLabel || '',
    noUpdatesLabel: ui.value.noUpdatesLabel || '',
    timelineReceivedLabel: ui.value.timelineReceivedLabel || '',
    timelineScanningLabel: ui.value.timelineScanningLabel || '',
    timelineNegotiatingLabel: ui.value.timelineNegotiatingLabel || '',
    timelineOffersLabel: ui.value.timelineOffersLabel || '',
    inProgressLabel: ui.value.inProgressLabel || '',
    liveRequestReceivedTemplate: ui.value.liveRequestReceivedTemplate || '',
    liveTokenConnectedTemplate: ui.value.liveTokenConnectedTemplate || '',
    liveOfferReadyTemplate: ui.value.liveOfferReadyTemplate || '',
    agentUpdateLabel: ui.value.agentUpdateLabel || '',
    finalizingLabel: ui.value.finalizingLabel || '',
    offerPriceLabel: ui.value.offerPriceLabel || '',
    savePrefixLabel: ui.value.savePrefixLabel || '',
    discountSuffixLabel: ui.value.discountSuffixLabel || '',
    emptyOffersTitle: ui.value.emptyOffersTitle || '',
    emptyOffersDescription: ui.value.emptyOffersDescription || '',
    liveTimeLabel: ui.value.liveTimeLabel || '',
    offerAtPriceDailyTemplate: ui.value.offerAtPriceDailyTemplate || '',
    offerAtPriceTotalTemplate: ui.value.offerAtPriceTotalTemplate || '',
    noteTotalTemplate: ui.value.noteTotalTemplate || '',
    noteDepositTemplate: ui.value.noteDepositTemplate || '',
    notePrepaymentTemplate: ui.value.notePrepaymentTemplate || '',
    offerDailyUnitLabel: ui.value.offerDailyUnitLabel || '',
    offerTotalUnitLabel: ui.value.offerTotalUnitLabel || '',
    openingBookingLabel: ui.value.openingBookingLabel || '',
    openBookingErrorLabel: ui.value.openBookingErrorLabel || '',
    standardRateLabel: ui.value.standardRateLabel || '',
  }))

  return {
    requestPage,
    requestBudgetTierLabels,
    requestTrackerUi,
  }
}
