import { useIntl } from "react-intl"

import { dt } from "@/lib/dt"

import Body from "@/components/TempDesignSystem/Text/Body"
import Caption from "@/components/TempDesignSystem/Text/Caption"
import useLang from "@/hooks/useLang"

import Card from "./Card"

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

import type { Dayjs } from "dayjs"

import type { SlideProps } from "@/types/components/blocks/surprises"

export default function Slide({ surprise }: SlideProps) {
  const lang = useLang()
  const intl = useIntl()

  const earliestExpirationDate = surprise.coupons
    .map(({ expiresAt }) => expiresAt)
    .filter((expiresAt): expiresAt is string => !!expiresAt)
    .reduce((earliestDate: Dayjs | null, expiresAt) => {
      const expiresAtDate = dt(expiresAt)
      if (!earliestDate) {
        return expiresAtDate
      }

      return earliestDate.isBefore(expiresAtDate) ? earliestDate : expiresAtDate
    }, null)

  return (
    <Card title={surprise.label}>
      <Body textAlign="center">{surprise.description}</Body>
      {earliestExpirationDate ? (
        <div className={styles.badge}>
          <Caption>
            {intl.formatMessage(
              { id: "Valid through {expirationDate}" },
              {
                expirationDate: dt(earliestExpirationDate)
                  .locale(lang)
                  .format("D MMM YYYY"),
              }
            )}
          </Caption>
        </div>
      ) : null}
    </Card>
  )
}
