import { dt } from "@/lib/dt"
import { serverClient } from "@/lib/trpc/server"

import { CreditCardAddIcon } from "@/components/Icons"
import Button from "@/components/TempDesignSystem/Button"
import Body from "@/components/TempDesignSystem/Text/Body"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import { getIntl } from "@/i18n"
import { getLang } from "@/i18n/serverContext"
import { formatPrice } from "@/utils/numberFormatting"

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

import type { BookingConfirmationPaymentDetailsProps } from "@/types/components/hotelReservation/bookingConfirmation/paymentDetails"

export default async function PaymentDetails({
  booking,
}: BookingConfirmationPaymentDetailsProps) {
  const intl = await getIntl()
  const lang = getLang()

  const linkedReservations = await Promise.all(
    //  TODO: How to handle partial failure (e.g. one booking can't be fetched)? Need UX/UI
    booking.linkedReservations.map(async (res) => {
      const confirmation = await serverClient().booking.confirmation({
        confirmationNumber: res.confirmationNumber,
      })
      return confirmation
    })
  )
  const grandTotal = linkedReservations.reduce((acc, res) => {
    return res ? acc + res.booking.totalPrice : acc
  }, booking.totalPrice)
  return (
    <div className={styles.details}>
      <Subtitle color="uiTextHighContrast" type="two">
        {intl.formatMessage({ id: "Payment details" })}
      </Subtitle>
      <div className={styles.payment}>
        <Body color="uiTextHighContrast">
          {intl.formatMessage(
            { id: "{amount} has been paid" },
            {
              amount: formatPrice(intl, grandTotal, booking.currencyCode),
            }
          )}
        </Body>
        <Body color="uiTextHighContrast">
          {dt(booking.createDateTime)
            .locale(lang)
            .format("ddd D MMM YYYY, hh:mm")}
        </Body>
        <Body color="uiTextHighContrast">
          {intl.formatMessage(
            { id: "{card} ending with {cardno}" },
            { card: "N/A", cardno: "N/A" }
          )}
        </Body>
      </div>
      <Button
        className={styles.btn}
        intent="text"
        size="small"
        theme="base"
        variant="icon"
        wrapping
      >
        <CreditCardAddIcon />
        {intl.formatMessage({ id: "Save card to profile" })}
      </Button>
    </div>
  )
}
