import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { 
    Box, IconButton, Grid, FormControl, TextField,
    Typography, Badge, Avatar,
} from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import {SnackbarNotice} from "../../functions";
import LoadingButton from "@mui/lab/LoadingButton";
import { MuiTelInput } from "mui-tel-input";

class CompanyDetails extends Component { 
    state = {
        companyFormData: {
            companyName: "",
            address: "",
            phoneNumber: "",
            website: "",
            image: "",
        },
        frame: null,
        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.savedCompanyDetails) {
            this.setState({
                companyFormData: {
                    companyName: this.props.savedCompanyDetails.companyName || "",
                    address: this.props.savedCompanyDetails.address || "",
                    phoneNumber: this.props.savedCompanyDetails.phoneNumber || "",
                    website: this.props.savedCompanyDetails.website || "",
                    image: this.props.savedCompanyDetails.image || "",
                }
            });
        }
    }

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

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

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

        frame.on("select", () => {
            const attachment = frame.state().get("selection").first().toJSON();
            this.setState(prevState => ({
                companyFormData: {
                    ...prevState.companyFormData,
                    "image": attachment.url,
                }
            }));
        });

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

    handleRemoveImage = () => {
        this.setState(prevState => ({
            companyFormData: {
                ...prevState.companyFormData,
                "image": null,
            }
        }));
    };

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

    handlePhoneChange = (newphone) => {
        this.setState(prevState => ({
            companyFormData: {
                ...prevState.companyFormData,
                "phoneNumber": newphone,
            }
        }));
    };

    SaveCompanyDetails = () => {
        const { companyFormData } = this.state;
        this.setState({ loading: true });
    
        const dataToSend = {};
        dataToSend.companyName = companyFormData.companyName;
        dataToSend.address = companyFormData.address;
        dataToSend.phoneNumber = companyFormData.phoneNumber;
        dataToSend.website = companyFormData.website;
        dataToSend.image = companyFormData.image;

        fetch(`${wpbAdmin.root}bookify/v1/save-company-details`, {
            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, companyFormData, snackbarOpen, snackbarMessage, snackbarType, loading } = this.state;

        return (
            <>
                <ThemeProvider theme={theme}>
                    <Box component="div" sx={{mb:"4em"}}>
                        <Typography variant="h3">{__("Company Details", "bookify")}</Typography>
                        <Typography variant="body1">{__("Manage your business information and branding.", "bookify")}</Typography>
                    </Box>
                    <Box component="form">
                        <Grid container spacing={4} direction="column">
                            <Grid item>
                                <Box mt={2} textAlign="-webkit-center">
                                    {companyFormData.image ? (
                                        <Badge
                                            overlap="circular"
                                            anchorOrigin={{ vertical: "top", horizontal: "right" }}
                                            badgeContent={
                                                <IconButton onClick={this.handleRemoveImage} color={"error"}>
                                                    <DeleteIcon fontSize="small" />
                                                </IconButton>
                                            }
                                        >
                                            <Avatar 
                                                alt="Staff image" 
                                                sx={{
                                                    width: "12rem",
                                                    height: "12rem",
                                                    border:"2px solid #BFD4D4"
                                                }} 
                                                src={companyFormData.image} 
                                                onClick={this.handleCompanyImage}
                                            />
                                        </Badge>
                                    ) : (
                                        <Box 
                                            border="2px dashed #BFD4D4" 
                                            textAlign="center" 
                                            sx={{
                                                width: "12rem", 
                                                height: "12rem", 
                                                borderRadius: "50%",
                                                display: "flex",
                                                alignItems: "center",
                                                justifyContent: "center"
                                            }}
                                            onClick={this.handleCompanyImage}
                                        >
                                            <Typography sx={{p:"30px", color:"#789595"}}>{__("Click here to upload company image", "bookify")}</Typography>
                                        </Box>
                                    )}
                                </Box>
                            </Grid>
                            <Grid item>
                                <FormControl fullWidth>
                                    <Typography variant="wpbkThemeLabel" component="label" htmlFor="company-name">
                                        {__("Company Name", "bookify")}
                                    </Typography>
                                    <TextField 
                                        id="company-name"
                                        type="text"
                                        name="companyName" 
                                        value={companyFormData.companyName}
                                        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 item container spacing={2} justifyContent="space-between">
                                <Grid item sx={{width:"50%"}}>
                                    <FormControl fullWidth>
                                        <Typography variant="wpbkThemeLabel" component="label" htmlFor="company-address">
                                            {__("Address", "bookify")}
                                        </Typography>
                                        <TextField 
                                            type="text" 
                                            name="address" 
                                            value={companyFormData.address}
                                            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 item sx={{width:"50%"}}>
                                    <FormControl fullWidth>
                                        <Typography variant="wpbkThemeLabel" component="label" htmlFor="company-phone">
                                            {__("Phone Number", "bookify")}
                                        </Typography>
                                        <MuiTelInput
                                            id="company-phone"
                                            inputProps={{ pattern: "[0-9]*" }}
                                            name="phoneNumber"
                                            value={companyFormData.phoneNumber}
                                            onChange={this.handlePhoneChange}
                                            defaultCountry="US"
                                            sx={{
                                                border: "1px solid #BFD4D4",
                                                height: "43px",
                                                borderRadius: "4px",
                                                justifyContent: "center",
                                                marginTop: "5px",
                                                "& 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",
                                                    mt: "0px"
                                                },
                                                "& fieldset": {
                                                    border: "none",
                                                },
                                            }}
                                        />
                                    </FormControl>
                                </Grid>
                            </Grid>
                            <Grid item>
                                <FormControl fullWidth>
                                    <Typography variant="wpbkThemeLabel" component="label" htmlFor="company-website">
                                        {__("Website", "bookify")}
                                    </Typography>
                                    <TextField 
                                        type="text" 
                                        placeholder="https://" 
                                        name="website" 
                                        value={companyFormData.website}
                                        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.SaveCompanyDetails} loading={loading} sx={{mt:"4em"}}>
                        {__("Save Details", "bookify")}
                    </LoadingButton>
                </ThemeProvider>
                <SnackbarNotice
                    state={this.state}
                    setState={this.setState.bind(this)}
                    open={snackbarOpen}
                    message={snackbarMessage}
                    type={snackbarType}
                />
            </>
        );
    }
}

export default CompanyDetails;