import { computed } from 'vue'
import { buildPublicLocaleSwitchContext, useRegisterPublicLocaleSwitchContext } from '~/composables/usePublicLocaleSwitchContext'
import { useResolvedPage } from '~/content/pages'
import { siteLocationsSnapshot } from '~/generated/site/locations'
import { buildResolvedPageSeo, sortByOrder } from '~/content/utils'
import { usePublicLocale } from '~/composables/usePublicLocale'
import { DEFAULT_PUBLIC_LOCALE } from '~/utils/public-locales'
import { normalizePublicInternalPath } from '~/utils/public-routes'

function buildMapEmbedUrl(location) {
  if (location?.mapEmbedUrl) {
    return location.mapEmbedUrl
  }

  const query = location?.address || location?.name || ''

  if (!query) {
    return ''
  }

  return `https://maps.google.com/maps?q=${encodeURIComponent(query)}&t=&z=15&ie=UTF8&iwloc=&output=embed`
}

function buildMapUrl(location) {
  if (location?.mapUrl) {
    return location.mapUrl
  }

  const query = location?.address || location?.name || ''

  if (!query) {
    return ''
  }

  return `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`
}

function sortLocations(left, right) {
  const leftAirport = left.isAirport ? 0 : 1
  const rightAirport = right.isAirport ? 0 : 1

  if (left.cityName !== right.cityName) {
    return String(left.cityName || left.city || '').localeCompare(String(right.cityName || right.city || ''))
  }

  if (leftAirport !== rightAirport) {
    return leftAirport - rightAirport
  }

  return String(left.name || '').localeCompare(String(right.name || ''))
}

function activeLocationsSnapshot() {
  return siteLocationsSnapshot.filter((location) => String(location?.locale || DEFAULT_PUBLIC_LOCALE) === DEFAULT_PUBLIC_LOCALE)
}

function resolveLocationLocalizedContent(location, locale = DEFAULT_PUBLIC_LOCALE) {
  const localized = location?.localizedContent && typeof location.localizedContent === 'object'
    ? location.localizedContent
    : {}

  return localized[locale] || localized[DEFAULT_PUBLIC_LOCALE] || {}
}

function buildContactLocations(locale = DEFAULT_PUBLIC_LOCALE) {
  return activeLocationsSnapshot()
    .filter((location) => location?.name)
    .map((location) => {
      const localizedContent = resolveLocationLocalizedContent(location, locale)

      return {
        ...location,
        name: localizedContent.name || location.name,
        cityName: localizedContent.cityName || location.cityName || location.city,
      }
    })
    .sort(sortLocations)
    .map((location) => ({
      id: location.code || location.slug || String(location.id),
      city: location.cityName || location.city || '',
      name: location.name,
      address: location.address,
      phone: location.phone,
      hours: location.workingHours,
      mapSrc: buildMapEmbedUrl(location),
      mapUrl: buildMapUrl(location),
    }))
}

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

export function useContactContent() {
  const contactPage = useResolvedPage('contact')
  const { locale } = usePublicLocale()
  const localeSwitchContext = computed(() => buildPublicLocaleSwitchContext(contactPage.value, { kind: 'list' }))

  useRegisterPublicLocaleSwitchContext(localeSwitchContext)

  const structuredContent = computed(() => contactPage.value?.structuredContent || {})
  const ui = computed(() => structuredContent.value.ui || {})
  const form = computed(() => structuredContent.value.form || {})

  const contactHero = computed(() => ({
    badge: ui.value.heroBadge || contactPage.value?.subtitle || '',
    title: contactPage.value?.title || '',
    subtitle: contactPage.value?.subtitle || '',
    description: contactPage.value?.excerpt || '',
  }))

  const contactUi = computed(() => ({
    locationsTitle: ui.value.locationsTitle || '',
    locationsDescription: ui.value.locationsDescription || '',
    viewMapLabel: ui.value.viewMapLabel || '',
    departmentsTitle: ui.value.departmentsTitle || '',
    departmentsDescription: ui.value.departmentsDescription || '',
    inquiryTitle: ui.value.inquiryTitle || '',
    inquiryDescription: ui.value.inquiryDescription || '',
    supportEmailLabel: ui.value.supportEmailLabel || '',
    supportPhoneLabel: ui.value.supportPhoneLabel || '',
    successTitle: ui.value.successTitle || '',
    successDescription: ui.value.successDescription || '',
    successButtonLabel: ui.value.successButtonLabel || '',
    mapModalCloseLabel: ui.value.mapModalCloseLabel || '',
    locationsEmptyTitle: ui.value.locationsEmptyTitle || '',
    locationsEmptyDescription: ui.value.locationsEmptyDescription || '',
  }))

  const contactForm = computed(() => ({
    labels: form.value.labels || {},
    placeholders: form.value.placeholders || {},
    submitLabel: form.value.submitLabel || '',
    submittingLabel: form.value.submittingLabel || '',
    phoneValidationMessage: form.value.phoneValidationMessage || '',
  }))

  const contactLocations = computed(() => buildContactLocations(locale.value))
  const contactDepartments = computed(() => sortByOrder(structuredContent.value.departments || [], 'order'))

  const contactSupportChannels = computed(() => {
    const explicitSupport = structuredContent.value.supportChannels || {}
    const supportDepartment = contactDepartments.value.find((department) => String(department.name || '').toLowerCase().includes('support'))
      || contactDepartments.value[0]
      || null

    return {
      emailLabel: explicitSupport.emailLabel || ui.value.supportEmailLabel || '',
      emailValue: explicitSupport.emailValue || supportDepartment?.email || '',
      phoneLabel: explicitSupport.phoneLabel || ui.value.supportPhoneLabel || '',
      phoneValue: explicitSupport.phoneValue || supportDepartment?.phone || '',
    }
  })

  return {
    contactPage,
    contactHero,
    contactUi,
    contactForm,
    contactLocations,
    contactDepartments,
    contactSupportChannels,
  }
}
