import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { 
    Dialog, DialogTitle, DialogContent, DialogActions, Box, 
    Divider, IconButton, Grid, FormControl, TextField,
    Typography, Badge, Avatar, Button
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import DeleteIcon from "@mui/icons-material/Delete";
import { SnackbarNotice } from "../../functions";
import LoadingButton from "@mui/lab/LoadingButton";
import { MuiTelInput } from "mui-tel-input";
import { ReactComponent as CustomerIconPlaceholder } from "../../assets/person-icon-placeholder.svg";

class AddCustomer extends Component { 
    state = { 
        addFormData: {
            fullName: "",
            phoneNumber: "",
            email: "",
            password: "",
            note: "",
            image: ""
        },
        editFormData: {
            fullName: "",
            phoneNumber: "",
            email: "",
            password: "",
            note: "",
            image: ""
        }, 
        errors: {
            fullName: false,
            phoneNumber: false,
            email: false,
            emailValidation: false,
            password: false,
        },
        frame: null,
        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",
                                },
                            }
                        }
                    ]
                },
            }
        })
    };

    componentDidUpdate(prevProps) {
        if (this.props.customerId && prevProps.customerId !== this.props.customerId) {
            this.loadCustomerData(this.props.customerId);
        }
    };

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

    handleInputChange = (event) => {
        const { name, value } = event.target;
        const formState = this.props.customerId ? "editFormData" : "addFormData";
        this.setState(prevState => ({
            [formState]: { ...prevState[formState], [name]: value },
            errors: { ...prevState.errors, [name]: false }
        }));
    };

    handlePhoneChange = (newphone) => {
        const formState = this.props.customerId ? "editFormData" : "addFormData";
        this.setState(prevState => ({
            [formState]: { ...prevState[formState], "phoneNumber": newphone },
            errors: { ...prevState.errors, "phoneNumber": false }
        }));
    };

    handleRemoveImage = () => {
        this.setState(prevState => ({
            [this.props.customerId ? "editFormData" : "addFormData"]: {
                ...prevState[this.props.customerId ? "editFormData" : "addFormData"],
                image: "",
            }
        }));
    };

    handleCustomerImage = () => {
        if (this.state.frame) {
            this.state.frame.open();
            return;
        }

        const frame = wp.media({
            title: "Select or Upload Customer Photo",
            button: {
                text: "Upload",
            },
            multiple: false,
        });

        frame.on("select", () => {
            const attachment = frame.state().get("selection").first().toJSON();
            this.setState(prevState => ({
                [this.props.customerId ? "editFormData" : "addFormData"]: {
                    ...prevState[this.props.customerId ? "editFormData" : "addFormData"],
                    image: attachment.url,
                }
            }));
        });

        frame.open();
        this.setState({ frame });
    }

    loadCustomerData = (customerId) => {
        const customer = this.props.fetchCustomerById(customerId);
        if (customer) {
            this.setState({ 
                editFormData: {
                    fullName: customer.customer_name,
                    email: customer.customer_email,
                    password: "",
                    phoneNumber: customer.customer_phone,
                    note: customer.customer_note,
                    image: customer.customer_img
                }
            });
        }
    }; 

    AddCustomerDetails = () => {
        const { addFormData, editFormData } = this.state;
        const { customerId, fetchCustomerData } = this.props;
        const dataToSend = {};

        const currentForm = customerId ? editFormData : addFormData;

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        const errors = {
            fullName: !currentForm.fullName,
            email: !currentForm.email,
            emailValidation: !emailRegex.test(currentForm.email),
            phoneNumber: !currentForm.phoneNumber,
        };

        if ( !customerId ) {
            errors.password = !currentForm.password;
        }

        this.setState({ errors });

        if ( errors.fullName || errors.email || errors.emailValidation || errors.phoneNumber || (!customerId && errors.password) ) {
            return;
        }

        this.setState({ loading: true });

        if (customerId) {
            dataToSend.customer_id = customerId;
        }
        dataToSend.customer_fullname = currentForm.fullName;
        dataToSend.customer_phone = currentForm.phoneNumber;
        dataToSend.customer_email = currentForm.email;
        dataToSend.customer_password = currentForm.password;
        dataToSend.customer_note = currentForm.note;
        dataToSend.customer_img = currentForm.image;

        const endpoint = customerId ? `${wpbAdmin.root}bookify/v1/update-customer` : `${wpbAdmin.root}bookify/v1/add-customer`;

        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({ 
                    addFormData: {
                        fullName: "",
                        phoneNumber: "",
                        email: "",
                        password: "",
                        note: "",
                        image: ""
                    },
                    errors: { fullName: false, email: false, password: false, phoneNumber: false },
                    snackbarOpen: true,
                    snackbarMessage: response.message,
                    snackbarType: "success",
                    loading: false,
                });
                fetchCustomerData();
                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 { open, customerId } = this.props;
        const { theme, addFormData, editFormData, errors, snackbarOpen, snackbarMessage, snackbarType, loading } = this.state;
        const currentForm = customerId ? 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" }}>
                            {customerId ? __("Edit Customer", "bookify") : __("Add Customer", "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>
                                        <Box mt={2} textAlign="-webkit-center">
                                            {currentForm.image ? (
                                                <Badge
                                                    overlap="circular"
                                                    anchorOrigin={{ vertical: "top", horizontal: "right" }}
                                                    badgeContent={
                                                        <IconButton onClick={this.handleRemoveImage} color={"error"}>
                                                            <DeleteIcon fontSize="small" />
                                                        </IconButton>
                                                    }
                                                >
                                                    <Avatar 
                                                        alt="Customer image" 
                                                        sx={{
                                                            width: "12rem",
                                                            height: "12rem",
                                                            border:"2px solid #BFD4D4"
                                                        }} 
                                                        src={currentForm.image} 
                                                        onClick={this.handleCustomerImage}
                                                    />
                                                </Badge>
                                            ) : (
                                                <Box 
                                                    border="2px dashed #BFD4D4" 
                                                    textAlign="center" 
                                                    sx={{
                                                        width: "12rem", 
                                                        height: "12rem", 
                                                        borderRadius: "50%",
                                                        display: "flex",
                                                        alignItems: "center",
                                                        justifyContent: "center",
                                                        flexDirection: "column"
                                                    }}
                                                    onClick={this.handleCustomerImage}
                                                >   
                                                    <CustomerIconPlaceholder />
                                                    <Typography sx={{p:"15px", color:"#789595"}}>{__("Click here to upload customer image", "bookify")}</Typography>
                                                </Box>
                                            )}
                                        </Box>
                                    </Grid>
                                    <Grid item>
                                        <FormControl fullWidth>
                                            <Typography variant="wpbkThemeLabel" component="label" htmlFor="customer-name">
                                                {__("Full Name ", "bookify")}
                                                <span style={{color:"#A61616"}}>*</span>
                                            </Typography>
                                            <TextField
                                                id="customer-name"
                                                error={errors.fullName}
                                                required
                                                type="text" 
                                                name="fullName" 
                                                value={currentForm.fullName}
                                                onChange={this.handleInputChange}
                                                sx={{
                                                    borderRadius: "5px",
                                                    justifyContent: "center",
                                                    "& fieldset": {
                                                        border: "none",
                                                    },
                                                    "& .MuiOutlinedInput-root": {
                                                        mt: "0px",
                                                        height: "43px",
                                                        border: "1px solid",
                                                        borderColor: errors.fullName ? "error.main" : "#BFD4D4",
                                                    },
                                                    "& .MuiInputBase-input": {
                                                        padding: "0px 14px"
                                                    }
                                                }}
                                            />
                                        </FormControl>
                                    </Grid>
                                    <Grid item container spacing={2} justifyContent="space-between">
                                        <Grid item sx={{width:"50%"}}>
                                            <FormControl fullWidth>
                                                <Typography variant="wpbkThemeLabel" component="label" htmlFor="customer-phone">
                                                    {__("Phone Number ", "bookify")}
                                                    <span style={{color:"#A61616"}}>*</span>
                                                </Typography>
                                                <MuiTelInput
                                                    id="customer-phone"
                                                    required
                                                    error={errors.phoneNumber}
                                                    inputProps={{ pattern: "[0-9]*" }}
                                                    name="phoneNumber"
                                                    value={currentForm.phoneNumber}
                                                    onChange={this.handlePhoneChange}
                                                    defaultCountry="US"
                                                    sx={{
                                                        borderRadius: "4px",
                                                        justifyContent: "center",
                                                        "& input[type=number]::-webkit-outer-spin-button": {
                                                            WebkitAppearance: "none",
                                                            margin: 0,
                                                        },
                                                        "& input[type=number]::-webkit-inner-spin-button": {
                                                            WebkitAppearance: "none",
                                                            margin: 0,
                                                        },
                                                        "& .MuiInputBase-input": {
                                                            pl: "0px"
                                                        },
                                                        "& .MuiOutlinedInput-root": {
                                                            pl: "8px",
                                                            height: "43px",
                                                            border: "1px solid",
                                                            borderColor: errors.phoneNumber ? "error.main" : "#BFD4D4",
                                                        },
                                                        "& fieldset": {
                                                            border: "none",
                                                        },
                                                    }}
                                                />
                                            </FormControl>
                                        </Grid>
                                        <Grid item sx={{width:"50%"}}>
                                            <FormControl fullWidth>
                                                <Typography variant="wpbkThemeLabel" component="label" htmlFor="customer-email">
                                                    {__("Email ", "bookify")}
                                                    <span style={{color:"#A61616"}}>*</span>
                                                </Typography>
                                                <TextField 
                                                    id="customer-email"
                                                    required
                                                    error={errors.email || errors.emailValidation}
                                                    helperText={errors.emailValidation && __("Please enter a valid email", "bookify")}
                                                    type="email" 
                                                    name="email" 
                                                    value={currentForm.email}
                                                    onChange={this.handleInputChange} 
                                                    sx={{
                                                        borderRadius: "5px",
                                                        justifyContent: "center",
                                                        "& fieldset": {
                                                            border: "none",
                                                        },
                                                        "& .MuiOutlinedInput-root": {
                                                            mt: "0px",
                                                            height: "43px",
                                                            border: "1px solid",
                                                            borderColor: errors.email ? "error.main" : "#BFD4D4",
                                                        },
                                                        "& .MuiInputBase-input": {
                                                            padding: "0px 14px"
                                                        }
                                                    }}
                                                />
                                            </FormControl>
                                        </Grid>
                                    </Grid>
                                    <Grid item>
                                        <FormControl fullWidth>
                                            <Typography variant="wpbkThemeLabel" component="label" htmlFor="customer-password">
                                                {__("Password ", "bookify")}
                                                <span style={{color:"#A61616"}}>*</span>
                                            </Typography>
                                            <TextField
                                                id="customer-password"
                                                required={!customerId}
                                                error={!customerId && errors.password}
                                                type="password" 
                                                name="password" 
                                                value={currentForm.password}
                                                onChange={this.handleInputChange}
                                                sx={{
                                                    borderRadius: "5px",
                                                    justifyContent: "center",
                                                    "& fieldset": {
                                                        border: "none",
                                                    },
                                                    "& .MuiOutlinedInput-root": {
                                                        mt: "0px",
                                                        height: "43px",
                                                        border: "1px solid",
                                                        borderColor: errors.password ? "error.main" : "#BFD4D4",
                                                    },
                                                    "& .MuiInputBase-input": {
                                                        padding: "0px 14px"
                                                    }
                                                }}
                                            />
                                        </FormControl>
                                    </Grid>
                                    <Grid item>
                                        <FormControl fullWidth>
                                            <Typography variant="wpbkThemeLabel" component="label" htmlFor="customer-note">
                                                {__("Note", "bookify")}
                                            </Typography>
                                            <TextField
                                                id="customer-note"
                                                multiline
                                                rows={4}
                                                name="note"
                                                value={currentForm.note}
                                                onChange={this.handleInputChange}
                                                sx={{
                                                    border: "1px solid #BFD4D4",
                                                    borderRadius: "4px",
                                                    justifyContent: "center",
                                                    "& fieldset": {
                                                        border: "none",
                                                    },
                                                }}
                                            />
                                        </FormControl>
                                    </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.AddCustomerDetails} loading={loading}>
                                {customerId ? __("Update Customer", "bookify") : __("Add Customer", "bookify")}
                            </LoadingButton>
                        </DialogActions>
                    </Dialog>
                </ThemeProvider>
                <SnackbarNotice
                    state={this.state}
                    setState={this.setState.bind(this)}
                    open={snackbarOpen}
                    message={snackbarMessage}
                    type={snackbarType}
                />
            </>
        );
    }
}

export default AddCustomer;
