import React, { useState, useEffect } from 'react';
import { Form } from 'react-final-form';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';
import { NavLink } from 'react-router-dom';
import qs from 'query-string';

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

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import CheckoutForm from 'components/forms/CheckoutForm';
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
import { pushRoute } from 'store/utils/routes';
import app from 'store/app';
import styleIdentifiers from './CheckoutStep3.module.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type CheckoutStep3Props = StateProps & DispatchProps & OwnProps;

const CheckoutStep3 = (props: CheckoutStep3Props) => {
  const { history, location } = props;
  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);
  const currentOrder = useSelector((state: StoreState) => state.order.current?.data);
  // Allow to dispatch actions
  const dispatch = useDispatch();

  const addPaymentMethod = data => dispatch(accountActions.addPaymentMethod.request.action(data));

  const loaderShow = () => dispatch(app.actions.loader.show.action());
  const loaderHide = () => dispatch(app.actions.loader.hide.action());
  const dialogSuccess = data => dispatch(app.actions.dialog.success.action(data));
  const dialogError = data => dispatch(app.actions.dialog.error.action(data));

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

  const handlePaymentIntent = async cardId => {
    const secret = currentOrder?.paymentIntent?.stripePaymentIntentData?.client_secret;

    loaderShow();

    if (!secret) return;

    const req = await stripe?.confirmCardPayment(secret, {
      // eslint-disable-next-line
      payment_method: cardId,
    });

    loaderHide();

    if (!req?.error) {
      history.push({
        pathname: pushRoute('orderSuccess'),
      });
    } else {
      console.log('req.error', req);
      dialogError({
        data: req?.error?.message,
      });
    }
  };

  const handleSubmit = async values => {
    if (values.cardMethod === 'other') {
      const cardElement = elements.getElement(CardElement);
      const { paymentMethod } = await stripe.createPaymentMethod({
        type: 'card',
        card: cardElement,
      });
      if (paymentMethod) {
        const dataStripe = {
          sPayMethodId: paymentMethod.id,
          nameOnCard: values.nameOnCard,
          default: values.default,
        };

        if (values.saveCard) {
          addPaymentMethod({
            data: dataStripe,
            callback: () => {
              handlePaymentIntent(dataStripe.sPayMethodId);
            },
            noFeedback: true,
            callbackError: e => {
              const message =
                e?.errors?.[0]?.data?.data?.message ||
                e?.errors?.[0]?.message ||
                'general.errors.stripeCardError';

              dialogError({
                data: message,
              });
            },
          });
        } else {
          handlePaymentIntent(dataStripe.sPayMethodId);
        }
      }
    } else {
      handlePaymentIntent(values.cardMethod);
    }
  };

  return (
    <div className={styles('checkout-step3')}>
      <h1>
        <TextItem path="pages.checkout.confirmationAndPayment" />
      </h1>
      <Form component={CheckoutForm} onSubmit={handleSubmit} customClassName={styles('form')} />
    </div>
  );
};

export default CheckoutStep3;
