/* global STRIPE_API_KEY */

import React from 'react'
import PropTypes from 'prop-types'
import PaymentPlan from 'react-uikit/payment-plan'
import TextInput from 'react-uikit/input-text'
import CouponBanner from './partials/coupon-banner'
import styles from './styles.scss'
import {densifyObj} from 'common-fe/utils'
import Debug from 'common-fe/utils/debug'
import BEMModule from 'utils/bem'
import {history} from 'router/history'
import routes from 'global/constants/routes'
import trackingIds from 'global/constants/tracking-ids'

const bem = new BEMModule(styles)

import Layout from 'components/layout'

class PaymentPage extends React.PureComponent {
    state = {coupon: null, planId: null}

    componentDidMount() {
        this.props.getPaymentPlans && this.props.getPaymentPlans()
    }

    onApplyCoupon = (value) => {
        if (!this.props.getCoupon || !value) {
            return
        }

        const couponId = value.trim()

        this.setState({coupon: {isLoading: true}})

        this.props
            .getCoupon({couponId})
            .then((coupon) => {
                this.setState({
                    coupon: {
                        ...coupon,
                        isLoading: false,
                    },
                })
            })
            .catch((err) => {
                Debug.log({err})

                this.setState({
                    coupon: {
                        error: 'Could not retrieve coupon',
                        isLoading: false,
                    },
                })
            })
    }

    checkout = (tokenObj = {}, metadata) => {
        const {id: token} = tokenObj
        const {
            billing_address_country_code: country,
            billing_address_state: state,
            billing_address_zip: zipCode,
            couponId,
            planId,
        } = metadata

        const {
            makePayment,
            user: {id: userId},
        } = this.props

        makePayment &&
            makePayment(
                densifyObj({
                    country,
                    couponId,
                    planId,
                    state,
                    token,
                    userId,
                    zipCode,
                })
            ).then(() => history.push(routes.HOME))
    }

    cancelSubscription = () => {
        const {
            cancelSubscriptions,
            user: {id: userId},
        } = this.props

        cancelSubscriptions &&
            cancelSubscriptions({userId}).then(() => history.push(routes.HOME))
    }

    render() {
        const {coupon} = this.state
        const {
            plans,
            user: {
                email,
                subscription: {
                    planId: subscribedPlan,
                    cancelled: isPlanCancelled,
                    endDate: nextBillDate,
                },
            },
        } = this.props

        const isValidCoupon = Boolean(coupon && !coupon.error && !!coupon.valid)
        const rootClasses = bem.classNames('c-payment-page')
        const layoutClasses = bem.classNames('c-payment-page__layout')
        const headingClasses = bem.classNames('c-payment-page__heading')
        const subHeadingClasses = bem.classNames('c-payment-page__sub-heading')
        const couponInputClasses = bem.classNames(
            'c-payment-page__coupon-input'
        )
        const couponInputButtonClasses = bem.classNames(
            'c-payment-page__coupon-input__button'
        )
        const couponBannerClasses = bem.classNames(
            'c-payment-page__coupon-banner'
        )
        const plansClasses = bem.classNames('c-payment-page__plans')

        return (
            <Layout.Main className={layoutClasses}>
                <div className={rootClasses}>
                    <h1 className={headingClasses}>EquitySim Pricing Plan</h1>

                    <h2 className={subHeadingClasses}>
                        Learn about the world of finance and develop your
                        trading skills in an opportunistic, holistic
                        environment.
                    </h2>

                    {(!isValidCoupon || coupon.error || coupon.isLoading) && (
                        <TextInput.WithButton
                            buttonClassName={couponInputButtonClasses}
                            buttonText="Apply"
                            className={couponInputClasses}
                            label="Enter discount code"
                            size="small"
                            trackingId={trackingIds.PAYMENT_APPLY_COUPON}
                            onButtonClick={this.onApplyCoupon}
                        />
                    )}

                    {coupon && (
                        <CouponBanner
                            className={couponBannerClasses}
                            coupon={this.state.coupon}
                        />
                    )}

                    <div className={plansClasses}>
                        {plans.map((plan) => (
                            <PaymentPlan
                                apiKey={STRIPE_API_KEY}
                                coupon={
                                    isValidCoupon &&
                                    coupon.metadata.planId === plan.id
                                        ? coupon
                                        : null
                                }
                                email={email}
                                isActive={
                                    plan.id === 'plan_EtjWXKxX2aKBgM'
                                        ? subscribedPlan === plan.id ||
                                          subscribedPlan ===
                                              'plan_EOFmZ5bajA0Zhh'
                                        : subscribedPlan === plan.id
                                }
                                isCancelled={
                                    plan.id === 'plan_EtjWXKxX2aKBgM'
                                        ? (isPlanCancelled &&
                                              subscribedPlan === plan.id) ||
                                          plan.id === 'plan_EOFmZ5bajA0Zhh'
                                        : isPlanCancelled &&
                                          subscribedPlan === plan.id
                                }
                                key={plan.id}
                                nextBillDate={nextBillDate}
                                plan={plan}
                                trackingId={
                                    isValidCoupon
                                        ? trackingIds.PAYMENT_SELECT_DISCOUNT_PRICE_PLAN
                                        : trackingIds.PAYMENT_SELECT_FULL_PRICE_PLAN
                                }
                                onCancelSubscription={this.cancelSubscription}
                                onCheckout={this.checkout}
                            />
                        ))}
                    </div>

                    <p>
                        If you have any questions or concerns, click on the chat
                        bubble in the bottom-right corner and let us know!
                    </p>
                </div>
            </Layout.Main>
        )
    }
}

PaymentPage.pageTitle = 'Pricing Plans'

PaymentPage.propTypes = {
    user: PropTypes.shape({
        id: PropTypes.string.isRequired,
        email: PropTypes.string,
        subscription: PropTypes.object,
    }).isRequired,
    cancelSubscriptions: PropTypes.func,
    getCoupon: PropTypes.func,
    getPaymentPlans: PropTypes.func,
    makePayment: PropTypes.func,
    plans: PropTypes.array,
}

export default PaymentPage
