import { computed, unref } from 'vue'
import { buildPublicLocaleSwitchContext, useRegisterPublicLocaleSwitchContext } from '~/composables/usePublicLocaleSwitchContext'
import { usePublicLocale } from '~/composables/usePublicLocale'
import { useResolvedPage } from '~/content/pages'
import { resolvePublicUiValue } from '~/i18n/public-ui'
import { PUBLIC_LOCALES } from '~/utils/public-locales'
import { buildRentCheckoutRoute, buildRentExtrasRoute, buildTrackRoute } from '~/utils/public-routes'

function buildFlowSeo(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 || 'index,follow'),
    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 buildRentExtrasPageSeo(locale = 'en') {
  const title = `${resolvePublicUiValue(locale, 'common.customizeExtras')} | Bent`
  const description = resolvePublicUiValue(locale, 'extras.preparingDescription')

  return {
    title,
    description,
    ogTitle: title,
    ogDescription: description,
    ogImage: '',
    robots: 'noindex,nofollow',
    canonical: null,
    hreflang: [],
    xDefault: null,
  }
}

export function buildCheckoutPageSeo(page) {
  return buildFlowSeo(page, { privateFlow: true })
}

export function buildTrackPageSeo(page, options = {}) {
  return buildFlowSeo(page, options)
}

export function useRentExtrasFlowContent(vehicleGroupIdRef) {
  const rentPage = useResolvedPage('rent')
  const vehicleGroupId = computed(() => Number(unref(vehicleGroupIdRef) || 0) || null)

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

    return buildPublicLocaleSwitchContext(rentPage.value, {
      kind: 'detail',
      sectionPath: '/rent',
      detailLocales: PUBLIC_LOCALES.map((entry) => entry.locale),
      pathsByLocale: buildPathsByLocale((entryLocale) => buildRentExtrasRoute(vehicleGroupId.value, {}, {
        locale: entryLocale,
      }).path),
    })
  })

  useRegisterPublicLocaleSwitchContext(localeSwitchContext)

  return {
    rentPage,
  }
}

export function useCheckoutFlowContent(vehicleGroupIdRef) {
  const checkoutPage = useResolvedPage('checkout')
  const vehicleGroupId = computed(() => Number(unref(vehicleGroupIdRef) || 0) || null)

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

    return buildPublicLocaleSwitchContext(checkoutPage.value, {
      kind: 'detail',
      sectionPath: '/rent',
      detailLocales: PUBLIC_LOCALES.map((entry) => entry.locale),
      pathsByLocale: buildPathsByLocale((entryLocale) => buildRentCheckoutRoute(vehicleGroupId.value, {}, {
        locale: entryLocale,
      }).path),
    })
  })

  useRegisterPublicLocaleSwitchContext(localeSwitchContext)

  return {
    checkoutPage,
  }
}

export function useTrackFlowContent(tokenRef) {
  const { locale } = usePublicLocale()
  const trackPage = useResolvedPage('track')
  const token = computed(() => String(unref(tokenRef) || '').trim())

  const localeSwitchContext = computed(() => buildPublicLocaleSwitchContext(trackPage.value, {
    kind: 'detail',
    sectionPath: '/track',
    detailLocales: PUBLIC_LOCALES.map((entry) => entry.locale),
    pathsByLocale: buildPathsByLocale((entryLocale) => buildTrackRoute(token.value, {}, {
      locale: entryLocale,
    }).path),
  }))

  useRegisterPublicLocaleSwitchContext(localeSwitchContext)

  const trackPortalUi = computed(() => ({
    missingTokenLabel: resolvePublicUiValue(locale.value, 'track.missingTokenLabel', trackPage.value?.structuredContent?.ui?.missingTokenLabel || ''),
    loadErrorLabel: resolvePublicUiValue(locale.value, 'track.couldNotLoadBooking', trackPage.value?.structuredContent?.ui?.loadErrorLabel || ''),
  }))

  return {
    trackPage,
    trackPortalUi,
  }
}
