import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import { 
    Dialog, DialogTitle, DialogContent, DialogActions, Box, 
    Divider, IconButton, Grid, FormControl, TextField, 
    FormControlLabel, Switch, Select, MenuItem, FormGroup, 
    Checkbox, Accordion, AccordionSummary, Typography, 
    AccordionDetails, ListItem, ListItemText, Button
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import copy from "copy-to-clipboard";
import {SnackbarNotice} from "../../functions";
import { Placeholders } from "../../functions";
import LoadingButton from "@mui/lab/LoadingButton";

class AddNotification extends Component { 
    state = { 
        notificationEvents: [
            "Appointment Requested",
            "Appointment Confirmed",
            "Appointment Cancelled",
            "Staff Created",
        ],
        addFormData: {
            notificationName: "",
            notificationEvent: "Appointment Requested",
            emailSubject: "",
            emailBody: "",
            emailToAdmin: true,
            emailToStaff: false,
            emailToCustomer: false, 
        },
        editFormData: {
            notificationName: "",
            notificationEvent: "",
            emailSubject: "",
            emailBody: "",
            emailToAdmin: "",
            emailToStaff: "",
            emailToCustomer: "", 
        },
        errors: {
            notificationName: false,
            emailSubject: false,
            emailBody: false,
        },
        snackbarOpen: false,
        snackbarMessage: "",
        snackbarType: "",
        loading: false,
        theme: createTheme({
            typography: {
                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",
                                },
                            }
                        }
                    ]
                },
                MuiMenuItem: {
                    styleOverrides: {
                        root: {
                            marginLeft: "3px",
                            marginRight: "3px",
                            paddingLeft: "10px",
                            paddingRight: "10px",
                            borderRadius: "8px"
                        },
                    },
                },
                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() {
        const ProLocation = window.ProLocation;

        if ( ProLocation ) {

            const index = Placeholders.findIndex(
                (item) => item.primary === '{appointment_note}'
            );

            Placeholders.splice(index + 1, 0, {primary: '{appointment_gmeet_link}', secondary: 'Google Meet Link(s)'});

            Placeholders.push(
                { primary: "{location_name}", secondary: "Location Name" },
                { primary: "{location_phone}", secondary: "Location Phone" },
                { primary: "{location_address}", secondary: "Location Address" },
                { primary: "{location_note}", secondary: "Location note" },
            );
        }
    }

    componentDidUpdate(prevProps) {
        if (this.props.notificationId && prevProps.notificationId !== this.props.notificationId) {
            this.loadNotificationData(this.props.notificationId);
        }
    }

    loadNotificationData = (notificationId) => {
        const notification = this.props.fetchNotificationById(notificationId);
        if (notification) {
            this.setState({ 
                editFormData: { 
                    notificationName: notification.notification_name, 
                    notificationEvent: notification.notification_event,
                    emailSubject: notification.notification_email_subject,
                    emailBody: notification.notification_email_body,
                    emailToAdmin: notification.email_sends_to.admin,
                    emailToStaff: notification.email_sends_to.staff,
                    emailToCustomer: notification.email_sends_to.customer,
                } 
            });
        }
    };

    handleClose = () => { this.props.onClose && this.props.onClose() };

    copyEmailCode = (text) => {
        copy(text);
        this.setState({ 
            snackbarOpen: true,
            snackbarMessage: `"${text}" copied into clipboard!`,
            snackbarType: "success",
        });
    }

    handleInputChange = (event) => {
        const { name, value, type, checked } = event.target;
        const formState = this.props.notificationId ? "editFormData" : "addFormData";
        this.setState(prevState => ({
            [formState]: { ...prevState[formState], [name]:  type === "checkbox" ? checked : value},
            errors: { ...prevState.errors, [name]: false }
        }));
    };

    handleEmailBody = (value) => {
        const formState = this.props.notificationId ? "editFormData" : "addFormData";
        this.setState(prevState => ({
            [formState]: { ...prevState[formState], "emailBody": value},
            errors: { ...prevState.errors, "emailBody": false }
        }));
    };

    AddNotificationDetails = () => {
        const { addFormData, editFormData } = this.state;
        const { notificationId, fetchNotificationData } = this.props;

        const currentForm = notificationId ? editFormData : addFormData;
        
        const errors = {
            notificationName: !currentForm.notificationName,
            emailSubject: !currentForm.emailSubject,
            emailBody: !currentForm.emailBody || currentForm.emailBody === "<p><br></p>",
        };

        this.setState({ errors });

        if ( errors.notificationName || errors.emailSubject || errors.emailBody ) {
            return;
        }

        this.setState({ loading: true });

        const dataToSend = {};
        
        if (notificationId) {
            dataToSend.notification_id = notificationId;
        }
        dataToSend.notificationName = currentForm.notificationName;
        dataToSend.notificationEvent = currentForm.notificationEvent;
        dataToSend.emailSubject = currentForm.emailSubject;
        dataToSend.emailBody = currentForm.emailBody;
        dataToSend.emailToAdmin = currentForm.emailToAdmin;
        dataToSend.emailToStaff = currentForm.emailToStaff;
        dataToSend.emailToCustomer = currentForm.emailToCustomer;

        const endpoint = notificationId ? `${wpbAdmin.root}bookify/v1/update-notification` : `${wpbAdmin.root}bookify/v1/add-notification`;
    
        fetch(endpoint, { 
            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,
                    addFormData: {
                        notificationName: "",
                        notificationEvent: "Appointment Requested",
                        emailSubject: "",
                        emailBody: "",
                        emailToAdmin: true,
                        emailToStaff: false,
                        emailToCustomer: false, 
                    },
                });
                this.handleClose();
                fetchNotificationData();
            } else {
                this.setState({ 
                    snackbarOpen: true, 
                    snackbarMessage: response.message, 
                    snackbarType:  "error",
                    loading: false,
                });
            }
        })
        .catch(error => {
            console.error("Error:", error);
            this.setState({ loading: false });
        })
    };

    render() {

        const { open, notificationId } = this.props;
        const { theme, addFormData ,editFormData, errors, notificationEvents, snackbarOpen, snackbarMessage, snackbarType, loading } = this.state;
        const currentForm = notificationId ? editFormData : addFormData;

        return (
            <>  
                <ThemeProvider theme={theme}>
                    <Dialog onClose={this.handleClose} open={open} fullWidth maxWidth={"sm"} sx={{height:"80%", padding:"4% 0%"}}>
                        <DialogTitle sx={{ display: "flex", alignItems: "center" }}>
                            {notificationId ? __("Edit Notification", "bookify") : __("Add Notification", "bookify")}
                            <IconButton
                                onClick={this.handleClose}
                                sx={{
                                    position: "absolute",
                                    right: 8,
                                    top: 8,
                                    color: (theme) => theme.palette.grey[500],
                                    "&:hover": {
                                        backgroundColor: "#DDEEEE",
                                    },
                                }}
                            >
                                <CloseIcon sx={{fontSize:"1rem"}} />
                            </IconButton>
                        </DialogTitle>
                                    
                        <Divider sx={{borderColor:"#DDEEEE"}} />

                        <DialogContent>
                            <Box component="form">
                                <Grid container spacing={3} direction="column">
                                    <Grid item>
                                        <FormControl fullWidth>
                                            <Typography variant="wpbkThemeLabel" component="label" htmlFor="notification-name">
                                                {__("Notification Name ", "bookify")}
                                                <span style={{color:"#A61616"}}>*</span>
                                            </Typography>
                                            <TextField 
                                                id="notification-name"
                                                error={errors.notificationName}
                                                required
                                                type="text" 
                                                name="notificationName" 
                                                value={currentForm.notificationName}
                                                onChange={this.handleInputChange}
                                                sx={{
                                                    borderRadius: "5px",
                                                    justifyContent: "center",
                                                    "& fieldset": {
                                                        border: "none",
                                                    },
                                                    "& .MuiOutlinedInput-root": {
                                                        mt: "0px",
                                                        height: "43px",
                                                        border: "1px solid",
                                                        borderColor: errors.notificationName ? "error.main" : "#BFD4D4",
                                                    },
                                                    "& .MuiInputBase-input": {
                                                        padding: "0px 14px"
                                                    }
                                                }}
                                            />
                                        </FormControl>
                                    </Grid>
                                    <Grid item>
                                        <FormControl fullWidth>
                                            <Typography variant="wpbkThemeLabel" component="label" htmlFor="bookify-notification-event">
                                                {__("Notification Events ", "bookify")}
                                                <span style={{color:"#A61616"}}>*</span>
                                            </Typography>
                                            <Select 
                                                id="bookify-notification-event" 
                                                name="notificationEvent" 
                                                value={currentForm.notificationEvent}  
                                                onChange={this.handleInputChange}
                                                sx={{
                                                    border: "1px solid #BFD4D4",
                                                    height: "43px",
                                                    borderRadius: "4px",
                                                    justifyContent: "center",
                                                    "& fieldset": {
                                                        border: "none",
                                                    },
                                                    "& .MuiInputBase-input": {
                                                        padding: "0px 14px",
                                                    },
                                                    "& .MuiOutlinedInput-root": {
                                                        mt: "0px",
                                                    },
                                                }}
                                            >
                                                {notificationEvents.map((value) => (
                                                    <MenuItem key={value} value={value}>
                                                        {value}
                                                    </MenuItem>
                                                ))}
                                            </Select>
                                        </FormControl>
                                    </Grid>
                                    <Grid item>
                                        <Typography variant="wpbkThemeLabel" component="label" htmlFor="email-subject">
                                                {__("Recipients ", "bookify")}
                                            </Typography>
                                        <FormGroup>
                                            <FormControlLabel name="emailToAdmin" checked={currentForm.emailToAdmin === "true" || currentForm.emailToAdmin === true} control={<Checkbox defaultChecked onChange={this.handleInputChange} sx={{"&.Mui-checked": {color:"#036666"}}}/>} label="Admin" />
                                            <FormControlLabel name="emailToStaff" checked={currentForm.emailToStaff === "true" || currentForm.emailToStaff === true} control={<Checkbox onChange={this.handleInputChange} sx={{"&.Mui-checked": {color:"#036666"}}}/>} label="Staff" />
                                            { currentForm.notificationEvent != "Staff Created" && (
                                                <FormControlLabel name="emailToCustomer"checked={currentForm.emailToCustomer  === "true" || currentForm.emailToCustomer === true} control={<Checkbox onChange={this.handleInputChange} sx={{"&.Mui-checked": {color:"#036666"}}}/>} label="Customer" />
                                            )}
                                        </FormGroup>
                                    </Grid>
                                    <Grid item>
                                        <FormControl fullWidth>
                                            <Typography variant="wpbkThemeLabel" component="label" htmlFor="email-subject">
                                                {__("Email Subject ", "bookify")}
                                                <span style={{color:"#A61616"}}>*</span>
                                            </Typography>
                                            <TextField 
                                                id="email-subject"
                                                error={errors.emailSubject}
                                                required
                                                type="text" 
                                                name="emailSubject" 
                                                value={currentForm.emailSubject}
                                                onChange={this.handleInputChange} 
                                                sx={{
                                                    borderRadius: "5px",
                                                    justifyContent: "center",
                                                    "& fieldset": {
                                                        border: "none",
                                                    },
                                                    "& .MuiOutlinedInput-root": {
                                                        mt: "0px",
                                                        height: "43px",
                                                        border: "1px solid",
                                                        borderColor: errors.emailSubject ? "error.main" : "#BFD4D4",
                                                    },
                                                    "& .MuiInputBase-input": {
                                                        padding: "0px 14px"
                                                    }
                                                }}
                                            />
                                        </FormControl>
                                    </Grid>
                                    <Grid item>
                                        <FormControl fullWidth>
                                            <Typography variant="wpbkThemeLabel" component="label" htmlFor="email-body">
                                                {__("Email Body ", "bookify")}
                                                <span style={{color:"#A61616"}}>*</span>
                                            </Typography>
                                            <ReactQuill 
                                                theme="snow" 
                                                id="email-body" 
                                                value={currentForm.emailBody} 
                                                onChange={(value) => this.handleEmailBody(value)}
                                            />
                                        </FormControl>
                                    </Grid>
                                    <Grid item>
                                        <Typography variant="wpbkThemeLabel" component="label">
                                            {__("Placeholders", "bookify")}
                                        </Typography>
                                        <Accordion sx={{boxShadow:"none"}}>
                                            <AccordionSummary expandIcon={<ExpandMoreIcon sx={{color:"#042626"}}/>} 
                                                sx={{
                                                    backgroundColor:"#F8FCFC", 
                                                    borderRadius: "5px",
                                                    border:"1px solid #BFD4D4", 
                                                    mt:"5px",
                                                    minHeight: "45px",
                                                    "&.Mui-expanded": {
                                                        minHeight: "45px",
                                                        borderBottomRightRadius: "0px",
                                                        borderBottomLeftRadius: "0px",
                                                    },
                                                    "& .MuiAccordionSummary-content": {
                                                        margin: 0,
                                                        "&.Mui-expanded": {
                                                            margin: 0
                                                        },
                                                    }
                                                }}
                                            >
                                                <Typography sx={{color:"#042626"}}>{__("Select", "bookify")}</Typography>
                                            </AccordionSummary>
                                            <AccordionDetails 
                                                sx={{
                                                    borderBottomRightRadius:"5px",
                                                    borderBottomLeftRadius:"5px",
                                                    border:"1px solid #BFD4D4",
                                                    borderTop: "none",
                                                    padding: "0px"
                                                }}
                                            >
                                                {Placeholders.map((code, index) => (
                                                    <React.Fragment key={index}>
                                                        <ListItem
                                                            secondaryAction={
                                                                <IconButton
                                                                    edge="end"
                                                                    onClick={() => this.copyEmailCode(code.primary)}
                                                                >
                                                                    <ContentCopyIcon />
                                                                </IconButton>
                                                            }
                                                        >
                                                            <ListItemText
                                                                primary={code.primary}
                                                                secondary={code.secondary}
                                                            />
                                                        </ListItem>
                                                        {index < Placeholders.length - 1 && <Divider variant="middle" />}
                                                    </React.Fragment>
                                                ))}
                                            </AccordionDetails>
                                        </Accordion>
                                    </Grid>
                                </Grid>
                            </Box>
                        </DialogContent>

                        <Divider sx={{borderColor:"#DDEEEE"}} />

                        <DialogActions sx={{m:2}}>
                            <Button variant="wpbkCancelbtn" onClick={this.handleClose}>
                                {__("Cancel", "bookify")}
                            </Button>
                            <LoadingButton variant="wpbkThemeModalBtn" onClick={this.AddNotificationDetails} loading={loading}>
                                {notificationId ? __("Update Notification", "bookify") : __("Add Notification", "bookify")}
                            </LoadingButton>
                        </DialogActions>
                    </Dialog>
                </ThemeProvider>
                <SnackbarNotice
                    state={this.state}
                    setState={this.setState.bind(this)}
                    open={snackbarOpen}
                    message={snackbarMessage}
                    type={snackbarType}
                />
            </>
        )
    }
}

export default AddNotification;