import TripadvisorIcon from "@scandic-hotels/design-system/Icons/TripadvisorIcon"

import Link from "@/components/TempDesignSystem/Link"
import { getIntl } from "@/i18n"
import { appendSlugToPathname } from "@/utils/appendSlugToPathname"

import styles from "./tripAdvisorLink.module.css"

import type { HotelTripAdvisor } from "@/types/hotel"

interface TripAdvisorLinkProps {
  tripAdvisor: NonNullable<HotelTripAdvisor>
}

export default async function TripAdvisorLink({
  tripAdvisor,
}: TripAdvisorLinkProps) {
  const intl = await getIntl()
  const { rating, numberOfReviews, reviews } = tripAdvisor
  const hasTripAdvisorData = !!(rating && numberOfReviews)

  if (!hasTripAdvisorData) {
    return null
  }

  const formattedTripAdvisorText = intl.formatMessage(
    {
      defaultMessage: "{rating} ({count} reviews on Tripadvisor)",
    },
    { rating, count: numberOfReviews }
  )

  const hasTripAdvisorIframeSrc = !!reviews.widgetScriptEmbedUrlIframe
  const tripAdvisorHref = hasTripAdvisorIframeSrc
    ? await appendSlugToPathname("reviews")
    : null

  if (!tripAdvisorHref) {
    return (
      <span className={styles.tripAdvisorText}>
        <TripadvisorIcon color="CurrentColor" />
        {formattedTripAdvisorText}
      </span>
    )
  }

  return (
    <Link
      textDecoration="underline"
      color="Text/Interactive/Secondary"
      href={tripAdvisorHref}
    >
      <TripadvisorIcon color="CurrentColor" />
      {formattedTripAdvisorText}
    </Link>
  )
}
