import { useIntl } from 'react-intl'
import { Label } from 'react-aria-components'

import { PaymentOptionsGroup } from '../PaymentOption/PaymentOptionsGroup'
import { PaymentOption } from '../PaymentOption/PaymentOption'
import { Typography } from '../../../components/Typography'

import styles from './selectPaymentMethod.module.css'

import {
  PAYMENT_METHOD_TITLES,
  PaymentMethodEnum,
} from '@scandic-hotels/common/constants/paymentMethod'

type PaymentMethod = {
  id: string
  truncatedNumber: string
  alias: string
  cardType: PaymentMethodEnum
}

type SelectPaymentMethodProps = {
  paymentMethods: PaymentMethod[]
  onChange: (value: string) => void
  formName: string
}

export function SelectPaymentMethod({
  paymentMethods,
  onChange,
  formName,
}: SelectPaymentMethodProps) {
  const intl = useIntl()
  const hasSavedCards = paymentMethods.length > 0

  if (!hasSavedCards) {
    return null
  }

  const mySavedCardsLabel = paymentMethods.length
    ? intl.formatMessage({
        id: 'payment.mySavedCards',
        defaultMessage: 'My saved cards',
      })
    : undefined

  const otherCardLabel = paymentMethods.length
    ? intl.formatMessage({
        id: 'common.other',
        defaultMessage: 'Other',
      })
    : undefined

  return (
    <section className={styles.section}>
      <PaymentOptionsGroup
        name={formName}
        className={styles.paymentOptionContainer}
        onChange={onChange}
        initalValue={
          //set credit card as default checked if user has no saved cards
          !hasSavedCards ? PAYMENT_METHOD_TITLES.card : undefined
        }
      >
        <Label className="sr-only">
          {intl.formatMessage({
            id: 'enterDetails.guarantee.cardOptions',
            defaultMessage: 'Card options',
          })}
        </Label>
        <Typography variant="Title/Overline/sm">
          <span>{mySavedCardsLabel}</span>
        </Typography>
        {paymentMethods?.map((paymentMethods) => {
          const label =
            PAYMENT_METHOD_TITLES[paymentMethods.cardType] ||
            paymentMethods.alias ||
            paymentMethods.cardType

          return (
            <PaymentOption
              type={paymentMethods.cardType}
              key={paymentMethods.id}
              value={paymentMethods.id}
              label={label}
              cardNumber={paymentMethods.truncatedNumber}
            />
          )
        })}
        <Typography variant="Title/Overline/sm">
          <span>{otherCardLabel}</span>
        </Typography>
        <PaymentOption
          value={PaymentMethodEnum.card}
          type={PaymentMethodEnum.card}
          label={intl.formatMessage({
            id: 'common.creditCard',
            defaultMessage: 'Credit card',
          })}
        />
      </PaymentOptionsGroup>
    </section>
  )
}
