import { useIntl } from 'react-intl'

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

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

import {
  PAYMENT_METHOD_TITLES,
  type 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 mySavedCardsLabel = intl.formatMessage({
    defaultMessage: 'MY SAVED CARDS',
  })

  return (
    <section className={styles.section}>
      <PaymentOptionsGroup
        name={formName}
        label={mySavedCardsLabel}
        className={styles.paymentOptionContainer}
        onChange={onChange}
      >
        {paymentMethods?.map((paymentMethods) => {
          const label =
            PAYMENT_METHOD_TITLES[paymentMethods.cardType] ||
            paymentMethods.alias ||
            paymentMethods.cardType

          return (
            <PaymentOption
              key={paymentMethods.id}
              value={paymentMethods.id as PaymentMethodEnum}
              label={label}
              cardNumber={paymentMethods.truncatedNumber}
            />
          )
        })}
      </PaymentOptionsGroup>
    </section>
  )
}
