import React, {useContext} from 'react';
import {NamedError, findErrorByName} from './named_error';
import {CardNumberElement, CardExpiryElement, CardCVCElement} from 'react-stripe-elements';
import {AppContext} from './app_context';
import {buildUrl} from './assets';

const createOptions = (placeholder, fieldName, errors) => {
  let classes = ['field', fieldName];

  const fieldMapping = {
    'card-number': 'cardNumber',
    'exp-date': 'cardExpiry',
    'cvc': 'cardCvc'
  };

  if (findErrorByName(errors, fieldMapping[fieldName]) != undefined) {
    classes.push('error');
  }

  return {
    placeholder: placeholder,
    classes: {
      base: classes.join(" "),
    },
    style: {
      base: {
        fontSize: '16px',
        color: '#484848',
        letterSpacing: '0.025em',
        '::placeholder': {
          fontFamily: '"Source Sans Pro", sans-serif'
        },
        fontFamily: '"Source Sans Pro", sans-serif'
      },
      invalid: {
        color: '#484848',
      },
    },
  };
};

export function StripeCreditCardForm(props) {
  const {onStripeFieldChange, errors} = props;
  const appContext = useContext(AppContext);
  const creditCardImageUrl = buildUrl(appContext, 'static/images/donate/credit-cards.png');

  return (
    <React.Fragment>
      <div className="split-form stripe-elements">
        <div className="field-row">
          <CardNumberElement
            {...createOptions('Card Number', 'card-number', errors)}
            onChange={onStripeFieldChange}
          />
        <img className='credit-cards' src={creditCardImageUrl} />
        </div>
        <div className="field-row">
          <CardExpiryElement
            {...createOptions('MM/YY', 'exp-date', errors)}
            onChange={onStripeFieldChange}
          />
          <CardCVCElement
            {...createOptions('CVC', 'cvc', errors)}
            onChange={onStripeFieldChange}
          />
        </div>
      </div>
    </React.Fragment>
  );
}
