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

import { CreditCard, Delete } from "@/components/Icons"
import AddCreditCardButton from "@/components/Profile/AddCreditCardButton"
import Button from "@/components/TempDesignSystem/Button"
import Body from "@/components/TempDesignSystem/Text/Body"
import Caption from "@/components/TempDesignSystem/Text/Caption"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import { getIntl } from "@/i18n"

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

export default async function CreditCardSlot() {
  const { formatMessage } = await getIntl()
  const creditCards = await serverClient().user.creditCards()

  return (
    <section className={styles.container}>
      <article className={styles.content}>
        <Subtitle type="two" color="black">
          {formatMessage({ id: "My credit cards" })}
        </Subtitle>
        <Body color="black">
          {formatMessage({
            id: "Check out the credit cards saved to your profile. Pay with a saved card when signed in for a smoother web experience.",
          })}
        </Body>
      </article>
      {creditCards?.length ? (
        <div className={styles.cardContainer}>
          {creditCards.map((card, idx) => (
            <CreditCardRow
              key={idx}
              cardType={card.attribute.cardType}
              truncatedNumber={card.attribute.truncatedNumber}
            />
          ))}
        </div>
      ) : null}
      <AddCreditCardButton />
    </section>
  )
}

function CreditCardRow({
  truncatedNumber,
  cardType,
}: {
  truncatedNumber: string
  cardType: string
}) {
  const maskedCardNumber = `**** ${truncatedNumber.slice(12, 16)}`
  return (
    <div className={styles.card}>
      <CreditCard color="black" />
      <Body textTransform="bold">{cardType}</Body>
      <Caption color="textMediumContrast">{maskedCardNumber}</Caption>
      <Button variant="icon" theme="base" intent="text">
        <Delete color="burgundy" />
      </Button>
    </div>
  )
}
