import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { 
    Typography, Box, Grid, FormControl, TextField,
} from "@mui/material";
import {SnackbarNotice} from "../../functions";
import LoadingButton from "@mui/lab/LoadingButton";

class NotificationSettings extends Component { 
    state = { 
        notificationFormData: {
            senderName: "",
            senderEmail: "",
        },
        snackbarOpen: false,
        snackbarMessage: "",
        snackbarType: "",
        loading: false,
        theme: createTheme({
            typography: {
                h3: {
                    fontSize: "2em",
                    fontWeight: "500",
                    textTransform: "capitalize",
                    color: "#042626",
                },
                body1: {
                    color: "#587373",
                    marginTop: "5px",
                },
                wpbkThemeLabel: {
                    color: "#042626",
                    fontSize: "15px",
                    fontWeight: "500",
                    paddingBottom: "5px",
                }
            },
            components: {
                MuiButton: {
                    variants: [
                        {
                            props: { variant: "wpbkThemeBtn" },
                            style: {
                                borderColor: "none",
                                backgroundColor: "#036666",
                                color: "#FFFFFF",
                                textTransform: "capitalize",
                                padding: "16px 0px",
                                width: "13em",
                                height: "45px",
                                "&:hover": {
                                    backgroundColor: "#025151",
                                    color: "#FFFFFF"
                                },
                                "&.Mui-disabled": {
                                    color: "#FFFFFF",
                                    opacity: 0.7,
                                },
                                "& .MuiLoadingButton-loadingIndicator": {
                                    color: "#FFFFFF",
                                }
                            },
                        },
                    ],
                },
            },
        }),
    };

    componentDidMount() {
        if (this.props.savedNotificationSettings) {
            this.setState({
                notificationFormData: {
                    senderName: this.props.savedNotificationSettings.senderName || "",
                    senderEmail: this.props.savedNotificationSettings.senderEmail || "",
                }
            });
        }
    }

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

    handleInputChange = (event) => {
        const { name, value } = event.target;
        this.setState(prevState => ({
            notificationFormData: {
                ...prevState.notificationFormData,
                [name]: value,
            }
        }));
    };

    SaveNotificationSettings = () => {
        const { notificationFormData } = this.state;
        this.setState({ loading: true });
    
        const dataToSend = {};
        dataToSend.senderName = notificationFormData.senderName;
        dataToSend.senderEmail = notificationFormData.senderEmail;
    
        fetch(`${wpbAdmin.root}bookify/v1/save-notification-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
                });
                this.handleClose();
            } else {
                this.setState({ 
                    snackbarOpen: true, 
                    snackbarMessage: response.message, 
                    snackbarType:  "error",
                    loading: false
                });
            }
        })
        .catch(error => {
            console.error("Error:", error);
            this.setState({ loading: false });
        })
    };

    render() { 
        const { theme, notificationFormData, snackbarOpen, snackbarMessage, snackbarType, loading } = this.state;

        return (
            <>
                <ThemeProvider theme={theme}>
                    <Box component="div" sx={{mb:"4em"}}>
                        <Typography variant="h3">{__("Notification Settings", "bookify")}</Typography>
                        <Typography variant="body1">{__("Customize email alerts and notification preferences.", "bookify")}</Typography>
                    </Box>
                    <Box component="form" sx={{display:"flex", gap:"3em"}}>
                        <Grid container spacing={4} direction="column">
                            <Grid item>
                                <FormControl fullWidth size="small">
                                    <Typography variant="wpbkThemeLabel" component="label" htmlFor="bookify-sender-name" >
                                        {__("Sender Name", "bookify")}
                                    </Typography>
                                    <TextField
                                        id="bookify-sender-name"
                                        type="text" 
                                        name="senderName"
                                        value={notificationFormData.senderName} 
                                        onChange={this.handleInputChange}
                                        sx={{
                                            border: "1px solid #BFD4D4",
                                            height: "43px",
                                            borderRadius: "5px",
                                            justifyContent: "center",
                                            marginTop: "5px",
                                            "& fieldset": {
                                                border: "none",
                                            },
                                            "& .MuiOutlinedInput-root": {
                                                mt: "0px",
                                            },
                                            "& .MuiInputBase-input": {
                                                padding: "0px 14px"
                                            }
                                        }}
                                    />
                                </FormControl>
                            </Grid>
                        </Grid>
                        <Grid container spacing={4} direction="column">
                            <Grid item>
                                <FormControl fullWidth size="small">
                                    <Typography variant="wpbkThemeLabel" component="label" htmlFor="bookify-sender-email" >
                                        {__("Sender Email", "bookify")}
                                    </Typography>
                                    <TextField
                                        id="bookify-sender-email"
                                        type="text"
                                        name="senderEmail"
                                        value={notificationFormData.senderEmail} 
                                        onChange={this.handleInputChange}
                                        sx={{
                                            border: "1px solid #BFD4D4",
                                            height: "43px",
                                            borderRadius: "5px",
                                            justifyContent: "center",
                                            marginTop: "5px",
                                            "& fieldset": {
                                                border: "none",
                                            },
                                            "& .MuiOutlinedInput-root": {
                                                mt: "0px",
                                            },
                                            "& .MuiInputBase-input": {
                                                padding: "0px 14px"
                                            }
                                        }}
                                    />
                                </FormControl>
                            </Grid>
                        </Grid>
                    </Box>
                    <LoadingButton variant="wpbkThemeBtn" onClick={this.SaveNotificationSettings} loading={loading} sx={{mt:"4em"}}>
                        {__("Save Settings", "bookify")}
                    </LoadingButton>
                </ThemeProvider>
                <SnackbarNotice
                    state={this.state}
                    setState={this.setState.bind(this)}
                    open={snackbarOpen}
                    message={snackbarMessage}
                    type={snackbarType}
                />
            </>
        );
    }
}

export default NotificationSettings;