import { computed } from 'vue'
import { reviewItems } from '~/generated/site/reviews'
import { resolveLocalizedCollectionByKey, useResolvedPage } from '~/content/pages'
import { buildResolvedPageSeo } from '~/content/utils'
import { usePublicLocale } from '~/composables/usePublicLocale'
import { resolvePublicUiValue } from '~/i18n/public-ui'

function formatPlatformLabel(platform, locale, pageUi) {
  if (platform === 'Google') {
    return pageUi?.googlePlatformLabel || resolvePublicUiValue(locale, 'reviews.googleReviews')
  }

  if (platform === 'Trustpilot') {
    return resolvePublicUiValue(locale, 'reviews.trustpilot')
  }

  if (platform === 'TripAdvisor') {
    return resolvePublicUiValue(locale, 'reviews.tripadvisor')
  }

  return platform
}

function splitReviewSubtitle(subtitle, locale, pageUi) {
  const [country, date] = String(subtitle || '')
    .split('•')
    .map((part) => part.trim())

  return {
    country: country || pageUi?.defaultCountry || resolvePublicUiValue(locale, 'reviews.guest'),
    date: date || pageUi?.defaultDate || resolvePublicUiValue(locale, 'reviews.recentReview'),
  }
}

function formatPlatformCount(count, hasRating, pageUi) {
  if (hasRating) {
    const template = count === 1
      ? pageUi?.ratedCountSingularTemplate
      : pageUi?.ratedCountPluralTemplate

    return String(template || '').replace('{count}', String(count))
  }

  const template = count === 1
    ? pageUi?.unratedCountSingularTemplate
    : pageUi?.unratedCountPluralTemplate

  return String(template || '').replace('{count}', String(count))
}

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

export function useReviewsContent() {
  const { locale } = usePublicLocale()
  const reviewsPage = useResolvedPage('reviews')

  const localizedReviewItems = computed(() => (
    resolveLocalizedCollectionByKey(
      reviewItems,
      locale.value,
      (item) => item?.contentKey || item?.slug || item?.id,
    )
  ))

  const pageUi = computed(() => reviewsPage.value?.structuredContent?.ui || {})

  const platformOrder = computed(() => [
    resolvePublicUiValue(locale.value, 'reviews.google'),
    resolvePublicUiValue(locale.value, 'reviews.trustpilot'),
    resolvePublicUiValue(locale.value, 'reviews.tripadvisor'),
  ])

  const platformColorMap = {
    Google: 'text-blue-600',
    Trustpilot: 'text-emerald-600',
    TripAdvisor: 'text-green-600',
  }

  const reviewPlatformStats = computed(() => {
    const grouped = localizedReviewItems.value.reduce((groups, item) => {
      const key = item.category || pageUi.value.defaultPlatform || resolvePublicUiValue(locale.value, 'reviews.customerReview')

      if (!groups.has(key)) {
        groups.set(key, {
          platform: key,
          count: 0,
          ratingTotal: 0,
          ratingCount: 0,
        })
      }

      const group = groups.get(key)
      group.count += 1

      const rating = Number(item.rating)

      if (Number.isFinite(rating) && rating > 0) {
        group.ratingTotal += rating
        group.ratingCount += 1
      }

      return groups
    }, new Map())

    return [...grouped.values()]
      .sort((left, right) => {
        const leftLabel = formatPlatformLabel(left.platform, locale.value, pageUi.value)
        const rightLabel = formatPlatformLabel(right.platform, locale.value, pageUi.value)
        const leftIndex = platformOrder.value.indexOf(leftLabel)
        const rightIndex = platformOrder.value.indexOf(rightLabel)

        if (leftIndex === -1 && rightIndex === -1) {
          return leftLabel.localeCompare(rightLabel)
        }

        if (leftIndex === -1) {
          return 1
        }

        if (rightIndex === -1) {
          return -1
        }

        return leftIndex - rightIndex
      })
      .map((item) => {
        const averageRating = item.ratingCount ? item.ratingTotal / item.ratingCount : 0

        return {
          label: formatPlatformLabel(item.platform, locale.value, pageUi.value),
          rating: item.ratingCount ? averageRating.toFixed(1) : null,
          count: item.count,
          countLabel: formatPlatformCount(item.count, item.ratingCount > 0, pageUi.value),
          color: platformColorMap[item.platform] || 'text-slate-600',
        }
      })
  })

  const reviewsHero = computed(() => ({
    badge: pageUi.value.heroBadge || reviewsPage.value?.subtitle || '',
    title: reviewsPage.value?.title || '',
    description: reviewsPage.value?.excerpt || '',
  }))

  const reviewCards = computed(() => localizedReviewItems.value.map((item) => {
    const { country, date } = splitReviewSubtitle(item.subtitle, locale.value, pageUi.value)

    return {
      id: item.contentKey || item.slug || item.id,
      name: item.author || pageUi.value.defaultName,
      country,
      date,
      platform: item.category || pageUi.value.defaultPlatform || resolvePublicUiValue(locale.value, 'reviews.customerReview'),
      rating: Number(item.rating || 0),
      text: item.body || item.excerpt || pageUi.value.defaultText,
      verified: item.verified !== false,
    }
  }))

  const reviewsEmptyState = computed(() => ({
    eyebrow: pageUi.value.emptyEyebrow || '',
    title: pageUi.value.emptyTitle || '',
    description: pageUi.value.emptyDescription || '',
  }))

  const reviewsFooterCopy = computed(() => ({
    verifiedLabel: pageUi.value.verifiedLabel || resolvePublicUiValue(locale.value, 'reviews.verified'),
    loadMoreLabel: pageUi.value.loadMoreLabel || resolvePublicUiValue(locale.value, 'common.loadMore'),
    title: pageUi.value.ctaTitle || '',
    description: pageUi.value.ctaDescription || '',
    primaryLabel: pageUi.value.ctaPrimaryLabel || '',
    primaryUrl: normalizePublicInternalPath(pageUi.value.ctaPrimaryUrl || '/vehicles', locale.value),
    secondaryLabel: pageUi.value.ctaSecondaryLabel || '',
    secondaryUrl: pageUi.value.ctaSecondaryUrl || '',
  }))

  return {
    reviewsPage,
    reviewPlatformStats,
    reviewsHero,
    reviewCards,
    reviewsEmptyState,
    reviewsFooterCopy,
  }
}
