import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { 
    Box, Grid, Typography, FormControl, FormControlLabel,
    Switch, Card, CardContent, CardActions
} from "@mui/material";
import PaypalPaymentModal from "./PaypalPaymentModal";
import { SnackbarNotice, GetProModal } from "../../functions";
import { ReactComponent as OnSiteIcon } from "../../assets/onsite-icon.svg";
import { ReactComponent as StripeIcon } from "../../assets/stripe-icon.svg";
import { ReactComponent as PaypalIcon } from "../../assets/paypal-icon.svg";

class PaymentDetails extends Component { 
    state = { 
        paymentGateways: {
            onsite: {
                toggled: true,
            },
            paypal: {
                toggled: false,
                clientId: "",
                secretKey: "",
            },
            stripe: {
                toggled: false,
                publishableKey: "",
                secretKey: "",
            },
        }, 
        errors: {
            paypalCI: false,
            paypalSK: false,
            stripePK: false,
            stripeSK: false
        },
        snackbarOpen: false,
        snackbarMessage: "",
        snackbarType: "",
        loading: false,
        proModalOpen: false,
        paypalModalOpen: false,
        paypalConfigured: false,
        stripeModalOpen: false,
        stripeConfigured: false,
        theme: createTheme({
            typography: {
                h3: {
                    fontSize: "2em",
                    fontWeight: "500",
                    textTransform: "capitalize",
                    color: "#042626",
                },
                body1: {
                    color: "#587373", 
                    marginTop: "5px"
                },
                wpbkPaymentTitle: {
                    color: "#042626",
                    fontSize: "16px",
                    fontWeight: 500
                },
                wpbkPaymentDes: {
                    color: "#587373",
                    fontSize: "13px"
                },
                wpbkPaymentStatus: {
                    color: "#036666",
                    fontSize: "13px",
                    fontWeight: 500
                },
                wpbkThemeLabel: {
                    color: "#042626",
                    fontSize: "15px",
                    fontWeight: "500",
                    paddingBottom: "5px",
                }
            },
            components: {
                MuiButton: {
                    variants: [
                        {
                            props: { variant: "wpbkThemeModalBtn" },
                            style: {
                                borderColor: "none",
                                backgroundColor: "#036666",
                                color: "#FFFFFF",
                                textTransform: "capitalize",
                                height: "40px",
                                "&:hover": {
                                    backgroundColor: "#025151",
                                    color: "#FFFFFF"
                                },
                                "&.Mui-disabled": {
                                    color: "#FFFFFF",
                                    opacity: 0.7,
                                },
                                "& .MuiLoadingButton-loadingIndicator": {
                                    color: "#FFFFFF",
                                }
                            },
                        },
                        {
                            props: { variant: "wpbkCancelbtn"},
                            style: {
                                textTransform: "capitalize",
                                height: "40px",
                                color: "#036666",
                                "&:hover": {
                                    backgroundColor: "#DDEEEE",
                                },
                            }
                        }
                    ]
                },
                MuiCard: {
                    variants: [
                        {
                            props: { variant: "wpbkPaymentCard" },
                            style: {
                                backgroundColor: "#F8FCFC",
                                border: "1px solid #BFD4D4",
                                width: "20em",
                                height: "11em",
                                padding: "19px",
                                display: "flex",
                                flexDirection: "column",
                                justifyContent: "space-between"
                            }
                        }
                    ],
                },
                MuiSwitch: {
                    styleOverrides: {
                        root: {
                            width: "40px",
                            height: "23px",
                            padding: "0px",
                            borderRadius: "13px"
                        },
                        switchBase: {
                            padding: "0px",
                            margin: "3px",
                            transitionDuration: "300ms",
                            "&.Mui-checked": {
                                transform: "translateX(17px)",
                                color: "#FFFFFF",
                                "& .MuiSwitch-thumb": {
                                    color: "#EBF8F8",
                                },
                                "& + .MuiSwitch-track": {
                                    backgroundColor: "#036666",
                                    opacity: 1,
                                    border: "none",
                                },
                                "&.Mui-disabled + .MuiSwitch-track": {
                                    opacity: 0.5,
                                },
                            },
                            "&.Mui-focusVisible .MuiSwitch-thumb": {
                                color: "#33cf4d",
                                border: "6px solid #FFFFFF",
                            },
                            "&.Mui-disabled .MuiSwitch-thumb": {
                                opacity: 0.5,
                            },
                            "&.Mui-disabled + .MuiSwitch-track": {
                                opacity: 0.7,
                            },
                            "& .MuiSwitch-input": {
                                border: "none",
                                background: "none",
                                display: "none"
                            }
                        },
                        thumb: {
                            width: "17px",
                            height: "17px",
                            color: "#036666"
                        },
                        track: {
                            borderRadius: "13px",
                            backgroundColor: "#EBF8F8",
                            opacity: 1,
                            transition: "background-color 500ms",
                            border: "1px solid #BFD4D4",
                            height: "auto"
                        },
                    },
                },
            },
        }),
    };

    componentDidMount() {
        if ( this.props.savedPaymentDetails ) {
            const paymentDetails = JSON.parse( this.props.savedPaymentDetails );

            this.setState({
                paymentGateways: paymentDetails || "",
                paypalConfigured: paymentDetails.paypal.clientId && paymentDetails.paypal.secretKey ? true : false, 
                stripeConfigured: paymentDetails.stripe.publishableKey && paymentDetails.stripe.secretKey ? true : false,
            });
        }
    }

    handleClose = () => this.props.onClose && this.props.onClose();

    handlePaymentChange = (event) => {
        const { name, type, checked, value } = event.target;
        const dataKey = event.target.getAttribute("data-key");

        this.setState(prevState => ({
            paymentGateways: {
                ...prevState.paymentGateways,
                [name]: {
                    ...prevState.paymentGateways[name],
                    [dataKey]: type === "checkbox" ? checked : value,
                },
            },
        }), () => {
            {type === "checkbox" && (
                this.SavePaymentSettings()
            )}
        });
    };

    SavePaymentSettings = ({ checkValidation = false, gateway = false } = {}) => {
        const { paymentGateways } = this.state;
        
        if ( checkValidation && ( gateway != false ) ) {

            let errors;

            if ( gateway == "paypal" ) {
                errors = {
                    paypalCI: !paymentGateways.paypal.clientId,
                    paypalSK: !paymentGateways.paypal.secretKey,
                };
            } 

            if ( gateway == "stripe" ) {
                errors = {
                    stripePK: !paymentGateways.stripe.publishableKey,
                    stripeSK: !paymentGateways.stripe.secretKey,
                };
            }

            errors = wp.hooks.applyFilters( "bookify_save_payment_settings_validation", errors, paymentGateways );
        
            this.setState({ errors });

            if (Object.values(errors).some(error => error)) {
                return;
            }
        }

        this.setState({ loading: true });
    
        const dataToSend = {};
        dataToSend.payment_gateways = JSON.stringify(paymentGateways);
    
        fetch(`${wpbAdmin.root}bookify/v1/save-payment-settings`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpApiSettings.nonce
            },
            body: JSON.stringify(dataToSend),
        })
        .then(response => response.json())
        .then((response) => {
            if ( response.success ) {
                this.setState({ 
                    snackbarOpen: true,
                    snackbarMessage: response.message,
                    snackbarType: "success",
                    loading: false,
                    paypalModalOpen: false,
                    stripeModalOpen: false,
                    paypalConfigured: true,
                    stripeConfigured: true,
                });
                this.handleClose();
            } else {
                this.setState({ 
                    snackbarOpen: true, 
                    snackbarMessage: response.message, 
                    snackbarType:  "error",
                    loading: false
                });
            }
        })
        .catch(error => {
            console.error("Error:", error);
            this.setState({ loading: false });
        })
    };

    handleProPopup = () => {
        this.setState({
            proModalOpen: true
        });
    }

    handleStripeModalOpen = () => {
        this.setState({
            stripeModalOpen: true
        });
    }

    handlePaypalModalOpen = () => {
        this.setState({
            paypalModalOpen: true
        });
    }

    render() { 
        const { theme, paymentGateways, errors, snackbarOpen, snackbarMessage, snackbarType, loading, proModalOpen, paypalModalOpen, stripeModalOpen, paypalConfigured, stripeConfigured } = this.state;

        const StripePaymentModal = window.StripePaymentModal;

        return (
            <>
                <ThemeProvider theme={theme}>
                    <Box component="div" sx={{mb:"4em"}}>
                        <Typography variant="h3">{__("Payment Settings", "bookify")}</Typography>
                        <Typography variant="body1">{__("Configure payment methods and manage secure transactions.", "bookify")}</Typography>
                    </Box>
                    <Box component="form">
                        <Grid container spacing={4} direction="row">
                            <Grid item>
                                <Card component="div" variant="wpbkPaymentCard">
                                    <CardContent sx={{display:"flex", flexDirection:"column", gap:"10px", p:"0px"}}>
                                        <OnSiteIcon/>
                                        <Typography variant="wpbkPaymentTitle">{__("On-Site Payment", "bookify")}</Typography>
                                        <Typography variant="wpbkPaymentDes">{__("Payment on site", "bookify")}</Typography>
                                    </CardContent>
                                    <CardActions sx={{justifyContent:"space-between", p:"0px"}}>
                                        <Typography variant="wpbkPaymentStatus">{paymentGateways.onsite.toggled ? __("Configured", "bookify") : __("Configure", "bookify")}</Typography>
                                        <FormControl size="small" sx={{color:"#354052 !important"}}>
                                            <FormControlLabel 
                                                control={<Switch color="primary" inputProps={{"data-key": "toggled"}}/>}
                                                labelPlacement="end" 
                                                name={"onsite"}
                                                checked={paymentGateways.onsite.toggled}
                                                onChange={!StripePaymentModal ? this.handleProPopup : this.handlePaymentChange}
                                                sx={{mr:"0px"}}
                                            />
                                        </FormControl>
                                    </CardActions>
                                </Card>
                            </Grid>
                            <Grid item>
                                <Card component="div" variant="wpbkPaymentCard">
                                    <CardContent sx={{display:"flex", flexDirection:"column", gap:"10px", p:"0px"}}>
                                        <PaypalIcon/>
                                        <Typography variant="wpbkPaymentTitle">{__("PayPal", "bookify")}</Typography>
                                        <Typography variant="wpbkPaymentDes">{__("Easy online payments", "bookify")}</Typography>
                                    </CardContent>
                                    <CardActions sx={{justifyContent:"space-between", p:"0px"}}>
                                        <Typography variant="wpbkPaymentStatus" onClick={this.handlePaypalModalOpen} sx={{cursor:"pointer"}}>{paymentGateways.paypal.clientId && paymentGateways.paypal.secretKey && paypalConfigured ? __("Configured", "bookify") : __("Configure", "bookify")}</Typography>
                                        {paymentGateways.paypal.clientId && paymentGateways.paypal.secretKey && paypalConfigured ? (
                                            <FormControl size="small" sx={{color:"#354052 !important"}}>
                                                <FormControlLabel 
                                                    control={<Switch color="primary" inputProps={{"data-key": "toggled"}}/>}
                                                    labelPlacement="end" 
                                                    name={"paypal"}
                                                    checked={paymentGateways.paypal.toggled}
                                                    onChange={this.handlePaymentChange}
                                                    sx={{mr:"0px"}}
                                                />
                                            </FormControl>
                                        ) : (
                                            <></>
                                        )}
                                    </CardActions>
                                </Card>
                            </Grid>
                            {StripePaymentModal ? (
                                <Grid item>
                                    <Card component="div" variant="wpbkPaymentCard">
                                        <CardContent sx={{display:"flex", flexDirection:"column", gap:"10px", p:"0px"}}>
                                            <StripeIcon/>
                                            <Typography variant="wpbkPaymentTitle">{__("Stripe", "bookify")}</Typography>
                                            <Typography variant="wpbkPaymentDes">{__("Secure payment processing", "bookify")}</Typography>
                                        </CardContent>
                                        <CardActions sx={{justifyContent:"space-between", p:"0px"}}>
                                            <Typography variant="wpbkPaymentStatus" onClick={this.handleStripeModalOpen} sx={{cursor:"pointer"}}>{paymentGateways.stripe.publishableKey && paymentGateways.stripe.secretKey && stripeConfigured ? __("Configured", "bookify") : __("Configure", "bookify")}</Typography>
                                            {paymentGateways.stripe.publishableKey && paymentGateways.stripe.secretKey && stripeConfigured ? (
                                                <FormControl size="small" sx={{color:"#354052 !important"}}>
                                                    <FormControlLabel 
                                                        control={<Switch color="primary" inputProps={{"data-key": "toggled"}}/>}
                                                        labelPlacement="end" 
                                                        name={"stripe"}
                                                        checked={paymentGateways.stripe.toggled}
                                                        onChange={this.handlePaymentChange}
                                                        sx={{mr:"0px"}}
                                                    />
                                                </FormControl>
                                            ) : (
                                                <></>
                                            )}
                                        </CardActions>
                                    </Card>
                                </Grid>
                            ) : (
                                <Grid item>
                                    <Card component="div" variant="wpbkPaymentCard">
                                        <CardContent sx={{display:"flex", flexDirection:"column", gap:"10px", p:"0px"}}>
                                            <Box sx={{display:"flex", justifyContent:"space-between", alignItems:"flex-start"}}>
                                                <StripeIcon/>
                                                <Typography sx={{padding:"4px 10px", backgroundColor:"#FFDD9A", color:"#735928", fontSize:"12px", fontWeight:600, borderRadius:"4px", m:"0px"}}>
                                                    {__("Pro","bookify")}
                                                </Typography>
                                            </Box>
                                            <Typography variant="wpbkPaymentTitle">{__("Stripe", "bookify")}</Typography>
                                            <Typography variant="wpbkPaymentDes">{__("Secure payment processing", "bookify")}</Typography>
                                        </CardContent>
                                        <CardActions sx={{justifyContent:"space-between", p:"0px"}}>
                                            <Typography variant="wpbkPaymentStatus">{__("Configure", "bookify")}</Typography>
                                            <FormControl size="small" sx={{color:"#354052 !important"}}>
                                                <FormControlLabel 
                                                    control={<Switch color="primary" inputProps={{"data-key": "toggled"}}/>}
                                                    labelPlacement="end" 
                                                    name={"stripe"}
                                                    checked={false}
                                                    onChange={this.handleProPopup}
                                                    sx={{mr:"0px"}}
                                                />
                                            </FormControl>
                                        </CardActions>
                                    </Card>
                                </Grid>
                            )}
                            
                            {wp.hooks.applyFilters( "bookify_add_payment_settings", [], this.state, this.setState.bind(this) )}
                        
                        </Grid>
                    </Box>
                </ThemeProvider>
                <SnackbarNotice
                    state={this.state}
                    setState={this.setState.bind(this)}
                    open={snackbarOpen}
                    message={snackbarMessage}
                    type={snackbarType}
                />
                <GetProModal 
                    open={proModalOpen}
                    onClose={() => this.setState({ proModalOpen: false })}
                />
                <PaypalPaymentModal
                    theme={theme}
                    open={paypalModalOpen}
                    onClose={() => this.setState({ paypalModalOpen: false })}
                    state={this.state}
                    setState={this.setState.bind(this)}
                    SavePaymentSettings={this.SavePaymentSettings}
                    errors={errors}
                    loading={loading}
                /> 
                {StripePaymentModal && (
                    <StripePaymentModal
                        theme={theme}
                        open={stripeModalOpen}
                        onClose={() => this.setState({ stripeModalOpen: false })}
                        state={this.state}
                        setState={this.setState.bind(this)}
                        SavePaymentSettings={this.SavePaymentSettings}
                        errors={errors}
                        loading={loading}
                    />
                )}
                
                
            </>
        );
    }
}

export default PaymentDetails;
