import * as React from 'react';
import PaymentMethodItem from '../PaymentMethodItem/PaymentMethodItem';

import CreditCardIcon from '../icons/CreditCardIcon/CreditCardIcon';
import PayPalIcon from '../icons/PayPalIcon/PayPalIcon';
import MercadoPagoIcon from '../icons/MercadoPagoIcon/MercadoPagoIcon';
import PagSeguroIcon from '../icons/PagSeguroIcon/PagSeguroIcon';
import YandexIcon from '../icons/YandexIcon/YandexIcon';
import IDealIcon from '../icons/IDealIcon/IDealIcon';
import SofortIcon from '../icons/SofortIcon/SofortIcon';
import AlipayIcon from '../icons/AlipayIcon/AlipayIcon';
import * as styles from './PaymentMethodList.scss';

interface IPaymentMethod {
  value: string;
  label: string;
}

interface IPaymentMethodListProps {
  radioButtonClassName?: string;
  paymentMethods: IPaymentMethod[];
  selectedMethod: string;
  activePaymentComponentNode?: JSX.Element;
  onPaymentMethodChanged: (pmId: string) => void;
}

export default class PaymentMethodList extends React.Component<IPaymentMethodListProps, any> {
  iconsMap = {
    creditCard: <CreditCardIcon/>,
    payPal: <PayPalIcon/>,
    mercadoPago: <MercadoPagoIcon/>,
    pagSeguro: <PagSeguroIcon/>,
    yandex: <YandexIcon/>,
    iDeal: <IDealIcon/>,
    sofort: <SofortIcon/>,
    alipay: <AlipayIcon/>
  };

  handleEnterKey = (value, e) => {
    const isActionKey = e.key === 'Enter' || e.key === ' ';
    if (isActionKey && this.props.onPaymentMethodChanged) {
      this.props.onPaymentMethodChanged(value);
    }
  }

  renderList() {
    return this.props.paymentMethods.map((method) => {
      const selected = this.props.selectedMethod === method.value;
      return (
        <div
          className={styles.wrapper}
          key={method.value}
          role="radiogroup"
          data-hook={`payment-method-item-${method.value}`}
          onKeyDown={this.handleEnterKey.bind(this, method.value)}
        >
          <PaymentMethodItem
            radioButtonClassName={this.props.radioButtonClassName}
            label={method.label}
            icon={this.iconsMap[method.value]}
            paymentMethodId={method.value}
            isSelected={selected}
            onPaymentMethodChanged={this.props.onPaymentMethodChanged}
          />
          {
            method.value === this.props.selectedMethod && this.props.activePaymentComponentNode
              ? <div className={styles.paymentComponent}>{this.props.activePaymentComponentNode}</div>
              : null
          }
        </div>
      );
    });
  }

  render() {
    return (
      <fieldset
        className={styles.paymentMethodList}
        data-hook="wcn-payment-method-list"
      >
        {this.renderList()}
      </fieldset>
    );
  }
}
