import React, { useState, useEffect } from 'react';
import { pushRoute } from 'store/utils/routes';
import { Form } from 'react-final-form';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';

// Import actions here
import accountActions from 'store/account/actions';

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import ProjectButton from 'components/items/ProjectButton';
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
import AddPaymentMethodForm from 'components/forms/AddPaymentMethodForm';

import AccountStructure from 'components/structure/AccountStructure';
import account from 'store/account';
import app from 'store/app';
import styleIdentifiers from './addPaymentMethod.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type AddPaymentMethodProps = StateProps & DispatchProps & OwnProps;

const AddPaymentMethod = (props: AddPaymentMethodProps) => {
  const { history } = props;
  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);
  // Allow to dispatch actions
  const dispatch = useDispatch();

  const addPaymentMethod = data => dispatch(accountActions.addPaymentMethod.request.action(data));
  const dialogError = data => dispatch(app.actions.dialog.error.action(data));

  const stripe = useStripe();
  const elements = useElements();

  const handleSubmit = async values => {
    const cardElement = elements.getElement(CardElement);

    const { paymentMethod } = await stripe.createPaymentMethod({
      type: 'card',
      card: cardElement,
    });

    if (paymentMethod) {
      const data = {
        sPayMethodId: paymentMethod.id,
        nameOnCard: values.nameOnCard,
        default: values.default,
      };

      addPaymentMethod({
        data,
        callback: () => {
          history.goBack();
        },
        noFeedback: true,
        success: 'forms.paymentMethod.addSuccess',
        callbackError: e => {
          const message =
            e?.errors?.[0]?.data?.data?.message ||
            e?.errors?.[0]?.message ||
            'general.errors.stripeCardError';

          dialogError({
            data: message,
          });
        },
      });
    }
  };

  return (
    <AccountStructure
      title="pages.account.payment"
      rightBack
      className={styles('add-payment-method')}
    >
      <Form component={AddPaymentMethodForm} onSubmit={handleSubmit} />
    </AccountStructure>
  );
};

export default AddPaymentMethod;
