//React imports
import React from "react";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
//Helpers
import axios from 'axios';
import StatusMessages, { useMessages } from '../helpers/StatusMessages'
//MUI Imports
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import CssBaseline from '@mui/material/CssBaseline';
import Box from '@mui/material/Box';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import { createTheme, ThemeProvider } from '@mui/material/styles';
//Styles
import '../App.css'
import './styles/Home.css'
//Strip Elements
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js";


const StripeRegister = () => {
    const [accessToken, setAccessToken] = useState("");
    const [promoCode, setPromoCode] = useState("");
    // const [error, setError] = useState('');
    const elements = useElements();
    const stripe = useStripe();
    const theme = createTheme();
    const navigate = useNavigate();
    const [messages, addMessage] = useMessages();
    const CARD_ELEMENT_OPTIONS = {
        style: {
            base: {
                color: "#32325d",
                fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                fontSmoothing: "antialiased",
                fontSize: "16px",
                "::placeholder": {
                    color: "#aab7c4",
                },
            },
            invalid: {
                color: "#fa755a",
                iconColor: "#fa755a",
            },
        },
    };

    useEffect(() => {
        window.scrollTo(0, 0)
        let accTok = localStorage.getItem('accessToken');
        if (accessToken === null) {
            navigate("/login");
        } else {
            setAccessToken(accTok);
        }
    }, [accessToken, navigate]);

    const handleSubmit = async (e) => {
        if (accessToken) {
            e.preventDefault();
            if (!stripe || !elements) {
                return;
            }
            addMessage('Creating Payment Intent...')
            //API call to create payment intent with server.
            axios.post(`/api/stripe/createSubscription`, promoCode, {
                headers: {
                    Authorization: 'Bearer ' + accessToken
                }
            }).then((response) => {
                const stripeClientSecret = response.data.clientSecret;
                addMessage('Payment Intent Created')
                const paymentIntent = stripe.confirmCardPayment(
                    stripeClientSecret, {
                    payment_method: {
                        card: elements.getElement(CardElement),
                    }
                }).then((result) => {
                    if (result.error) {
                        addMessage(result.error.message)
                        return;
                    }
                    addMessage(`PaymentIntent (${paymentIntent.id}): ${paymentIntent.status}`)
                    addMessage('Payment Success!')
                    setTimeout(navigate('/registration/success'), 3000)
                    // Successful subscription payment

                })
            }).catch(err => {
                addMessage(`<span class="text-danger">${err.response.data}</span>`);
            });;
        }
    }

    return (
        <div>
            <ThemeProvider theme={theme}>
                <Container component="main" maxWidth="sm">
                    <CssBaseline />
                    <div className="w-100 bg-white rounded-3 shadow-sm">
                        <Box
                            sx={{
                                p: 5,
                                marginTop: 8,
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                            }}
                            className='w-100 rounded-3'
                        >
                            <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
                                <LockOutlinedIcon />
                            </Avatar>
                            <Typography component="h1" variant="h5">
                                Register Payment Info
                            </Typography>
                            <Box noValidate sx={{ mt: 2 }} className="w-75">
                                <form onSubmit={handleSubmit} className="w-100" id="payment-form">
                                    <label htmlFor="card-element">Card Info</label>
                                    <CardElement id="card-element" options={CARD_ELEMENT_OPTIONS} className="p-3 mb-4 bg-light" />
                                    <div id="card-element-errors" role="alert"></div>
                                    <label htmlFor="promoCode">Promo Code</label>
                                    <input
                                        id="promoCode"
                                        type="text"
                                        className="form-control rounded my-3 input-group rounded w-100 bg-light p-2"
                                        placeholder="Optional"
                                        aria-label="Text"
                                        aria-describedby="Text"
                                        onChange={(event) => {
                                            setPromoCode(event.target.value);
                                        }}
                                    />
                                    <div className="d-flex justify-content-center">
                                        <Button
                                            type="submit"
                                            className='w-50'
                                            variant="contained"
                                            sx={{ mt: 5, mb: 2, bgcolor: "#EEB2A5" }}
                                        >
                                            Register Card
                                        </Button>
                                    </div>
                                </form>
                                <StatusMessages messages={messages} />
                            </Box>
                        </Box>
                    </div>
                </Container>
            </ThemeProvider>

            <div className="d-flex justify-content-center" maxWidth="sm">
                <div className="w-50 my-5 mx-2 p-4 bg-grey rounded-3">
                    <div className="row justify-content-md-center">
                        <div className="col-md-5 mb-4">
                            <h1 className="mb-5">MONTHLY <br /> MEMBERSHIP</h1>
                            <div className="col-sm-6 col-md-5 col-md-offset-1 col-lg-offset-2 col-lg-4 w-100">
                                <div className="price-info-box py-5 px-5 mb-4 rounded-3">
                                    <h2><span lang="EN-CA" data-contrast="auto"><span>$18</span></span></h2>
                                    <h3 ><span lang="EN-CA" data-contrast="auto"><span >30 days</span></span></h3>
                                    <p>Take advantage of all member benefits.&nbsp;Membership available on April 11.</p>
                                </div>
                            </div>
                            <table className="table-responsive w-100">
                                <caption className="fst-italic">Tier Benefits</caption>
                                <tbody>
                                    <tr className="pricing-table">
                                        <td>Unlocking fee</td>
                                        <td><strong>$0</strong></td>
                                    </tr>
                                    <tr className="pricing-table">
                                        <td>Regular HELLO VELO – 0 to 45 min</td>
                                        <td><strong>Unlimited</strong></td>
                                    </tr>
                                    <tr className="pricing-table">
                                        <td>Regular HELLO VELO – 45 min +</td>
                                        <td><span><strong>10</strong></span><strong>₵/minute</strong></td>
                                    </tr>
                                    <tr className="pricing-table">
                                        <td>Electric HELLO VELO</td>
                                        <td><span><strong>12</strong></span><strong>₵/minute</strong></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}
export default (StripeRegister);