import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { 
    Dialog, DialogTitle, DialogContent, DialogActions, Divider,
    IconButton, Grid, FormControl, TextField, Tooltip,
    Select, MenuItem, Box, Typography, Badge, Avatar, Button,
    InputAdornment, FormControlLabel, Chip, Autocomplete, Switch
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import DeleteIcon from "@mui/icons-material/Delete";
import {SnackbarNotice} from "../../functions";
import currencies from "../../currencies.json";
import LoadingButton from "@mui/lab/LoadingButton";
import InfoIcon from "@mui/icons-material/Info";
import { ReactComponent as ServiceIconPlaceholder } from "../../assets/service-icon-placeholder.svg";

class AddService extends Component { 
    state = { 
        allLocations: [],
        snackbarOpen: false,
        snackbarMessage: "",
        snackbarType: "success",
        loading: false,
        addFormData: {
            serviceName: "",
            price: "",
            category: "",
            location: [],
            image: "",
            toggleGoogleMeet: false,
            toggleZoomMeeting: false,
            note: "",
        },
        editFormData: {
            serviceName: "",
            price: "",
            category: "",
            location: [],
            image: "",
            toggleGoogleMeet: false,
            toggleZoomMeeting: false,
            note: "",
        },
        errors: { 
            serviceName: false,
            price: false,
            category: 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 ) {
            this.fetchLocationData();
        }
    }

    componentDidUpdate(prevProps) {
        if ( prevProps.generalGmeet !== this.props.generalGmeet ) {
            this.setState(prevState => ({
                addFormData: {
                    ...prevState.addFormData,
                    toggleGoogleMeet: this.props.generalGmeet
                },
                editFormData: {
                    ...prevState.editFormData,
                    toggleGoogleMeet: this.props.generalGmeet
                }
            }));
        }

        if (this.props.serviceId && prevProps.serviceId !== this.props.serviceId) {
            this.loadServiceData(this.props.serviceId);
        }
    }

    handleClose = () => this.props.onClose && this.props.onClose();

    fetchLocationData = () => {
        fetch(`${wpbAdmin.root}bookify/v1/get-locations`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpApiSettings.nonce
            }
        })
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                allLocations: data.locations,
            });
        })
        .catch((error) => {
            console.error("Error fetching data:", error);
        });
    };

    handleInputChange = (event) => {
        const { name, value, type, checked } = event.target;
        const formState = this.props.serviceId ? "editFormData" : "addFormData";
    
        this.setState((prevState) => ({
            [formState]: { 
                ...prevState[formState], 
                [name]: type === "checkbox" ? checked : value 
            },
            errors: { 
                ...prevState.errors, 
                [name]: false 
            }
        }));
    };

    handleLocationChange = (event, value) => {
        const formState = this.props.serviceId ? "editFormData" : "addFormData";
        this.setState(prevState => ({
            [formState]: { ...prevState[formState], location: value },
            errors: { ...prevState.errors, location: [] }
        })); 
    };

    loadServiceData = (serviceId) => {
        const service = this.props.fetchServiceById(serviceId);
        if (service) {
            const serviceLocationIds = service.service_location ? service.service_location : [];
            const selectedLocations = this.state.allLocations.filter(loc => serviceLocationIds.includes(loc.id));
    
            this.setState({ 
                editFormData: { 
                    serviceName: service.service_name, 
                    price: service.service_price,
                    category: service.service_category,
                    location: selectedLocations,
                    image: service.service_img,
                    toggleGoogleMeet: service.service_gmeet,
                    toggleZoomMeeting: service.service_zoom,
                    note: service.service_note,
                } 
            });
        }
    };  

    handleServiceSubmit = () => {
        const { addFormData, editFormData } = this.state;
        const { serviceId, fetchServiceData } = this.props;
        const GoogleConnectBtn = window.GoogleConnectBtn;
        const ZoomMeeting = window.ZoomMeeting;
        const ProLocation = window.ProLocation;

        const dataToSend = {};

        const currentForm = serviceId ? editFormData : addFormData;

        const errors = {
            serviceName: !currentForm.serviceName,
            price: !currentForm.price,
            category: currentForm.category != "" ? false : true,
        };

        this.setState({ errors });

        if (errors.serviceName || errors.price || errors.category) {
            return;
        }

        this.setState({ loading: true });

        const selectedLocationIds = currentForm.location.map(loc => loc.id);

        if ( serviceId ) {
            dataToSend.service_id = serviceId;
        }
        if ( GoogleConnectBtn ) {
            dataToSend.service_gmeet = currentForm.toggleGoogleMeet;
        }
        if ( ZoomMeeting ) {
            dataToSend.service_zoom = currentForm.toggleZoomMeeting;
        }
        if ( ProLocation ) {
            dataToSend.service_location = JSON.stringify(selectedLocationIds);
        }
        dataToSend.service_name = currentForm.serviceName;
        dataToSend.service_price = currentForm.price;
        dataToSend.service_category = currentForm.category;
        dataToSend.service_img = currentForm.image;
        dataToSend.note = currentForm.note;

        const endpoint = this.props.serviceId ? `${wpbAdmin.root}bookify/v1/update-service` : `${wpbAdmin.root}bookify/v1/add-service`;
        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: { 
                        serviceName: "", 
                        price: "", 
                        category: "",
                        location: [],
                        image: "",
                        toggleGoogleMeet: false,
                        note: "",
                    },
                    errors: { serviceName: false, price: false, category: false },
                    snackbarOpen: true,
                    snackbarMessage: response.message,
                    snackbarType: "success",
                    loading: false,
                });
                this.handleClose();
                fetchServiceData();
            } else {
                this.setState({ 
                    snackbarOpen: true,
                    snackbarMessage: response.message,
                    snackbarType: "error",
                    loading: false,
                });
            }
        })
        .catch(error => {
            console.error("Error:", error);
            this.setState({ loading: false });
        })
    }

    handleRemoveImage = () => {
        this.setState(prevState => ({
            [this.props.serviceId ? "editFormData" : "addFormData"]: {
                ...prevState[this.props.serviceId ? "editFormData" : "addFormData"],
                image: "",
            }
        }));
    };

    handleServiceImage = () => {
        if (this.state.frame) {
            this.state.frame.open();
            return;
        }

        const frame = wp.media({
            title: "Select or Upload Service Photo",
            button: {
                text: "Upload",
            },
            multiple: false,
        });

        frame.on("select", () => {
            const attachment = frame.state().get("selection").first().toJSON();
            this.setState(prevState => ({
                [this.props.serviceId ? "editFormData" : "addFormData"]: {
                    ...prevState[this.props.serviceId ? "editFormData" : "addFormData"],
                    image: attachment.url,
                }
            }));
        });

        frame.open();
        this.setState({ frame });
    }

    render() { 
        const { open, AllCategories, serviceId, currency, gmeetDisable, zoomDisable } = this.props;
        const { theme, addFormData, editFormData, errors, snackbarOpen, snackbarMessage, snackbarType, allLocations, loading } = this.state;
        const currentForm = serviceId ? editFormData : addFormData;
        const matchedCurrency = Object.values(currencies).find(eachCurrency => eachCurrency.code === currency);

        const ProLocation = window.ProLocation;
        const GoogleConnectBtn = window.GoogleConnectBtn;
        const ZoomMeeting = window.ZoomMeeting;

        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"}}>
                            {serviceId ? __("Edit Service", "bookify") : __("Add Service", "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>
                            <Grid container spacing={3}>
                                <Grid item xs={12}>
                                        <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="Staff image" 
                                                        sx={{
                                                            width: "12rem",
                                                            height: "12rem",
                                                            border:"2px solid #BFD4D4"
                                                        }} 
                                                        src={currentForm.image} 
                                                        onClick={this.handleServiceImage}
                                                    />
                                                </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.handleServiceImage}
                                                >   
                                                    <ServiceIconPlaceholder />
                                                    <Typography sx={{p:"15px", color:"#789595"}}>{__("Click here to upload service image", "bookify")}</Typography>
                                                    
                                                </Box>
                                            )}
                                        </Box>
                                    </Grid>
                                <Grid item xs={12}>
                                    <FormControl fullWidth>
                                        <Typography variant="wpbkThemeLabel" component="label" htmlFor="service-name">
                                            {__("Service Name ", "bookify")}
                                            <span style={{color:"#A61616"}}>*</span>
                                        </Typography>
                                        <TextField
                                            id="service-name"
                                            required
                                            error={errors.serviceName}
                                            type="text"
                                            name="serviceName"
                                            value={currentForm.serviceName}
                                            onChange={this.handleInputChange}
                                            sx={{
                                                borderRadius: "5px",
                                                justifyContent: "center",
                                                "& fieldset": {
                                                    border: "none",
                                                },
                                                "& .MuiOutlinedInput-root": {
                                                    mt: "0px",
                                                    height: "43px",
                                                    border: "1px solid",
                                                    borderColor: errors.serviceName ? "error.main" : "#BFD4D4",
                                                },
                                                "& .MuiInputBase-input": {
                                                    padding: "0px 14px"
                                                }
                                            }}
                                        />
                                    </FormControl>
                                </Grid>
                                <Grid item xs={12}>
                                    <FormControl fullWidth>
                                        <Typography variant="wpbkThemeLabel" component="label" htmlFor="service-price">
                                            {__("Price ", "bookify")}
                                            <span style={{color:"#A61616"}}>*</span>
                                        </Typography>
                                        <TextField
                                            id="service-price"
                                            required
                                            error={errors.price}
                                            type="number"
                                            name="price"
                                            value={currentForm.price}
                                            onChange={this.handleInputChange}
                                            InputProps={{
                                                startAdornment: (
                                                    <InputAdornment position="start">
                                                        {matchedCurrency.symbol_native}
                                                    </InputAdornment>
                                                )
                                            }}
                                            inputProps={{
                                                min: 0
                                            }}
                                            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": {
                                                    mt: "0px",
                                                    height: "43px",
                                                    border: "1px solid",
                                                    borderColor: errors.price ? "error.main" : "#BFD4D4",
                                                },
                                                "& fieldset": {
                                                    border: "none",
                                                },
                                            }}
                                        />
                                    </FormControl>
                                </Grid>
                                <Grid item xs={12}>
                                    <FormControl fullWidth>
                                        <Typography variant="wpbkThemeLabel" component="label" htmlFor="bookify-all-categories">
                                            {__("Category ", "bookify")}
                                            <span style={{color:"#A61616"}}>*</span>
                                        </Typography>
                                        <Select
                                            id="bookify-all-categories" 
                                            required 
                                            error={errors.category}
                                            name="category" 
                                            value={currentForm.category} 
                                            onChange={this.handleInputChange}
                                            sx={{
                                                borderRadius: "4px",
                                                justifyContent: "center",
                                                "& fieldset": {
                                                    border: "none",
                                                },
                                                "& .MuiInputBase-input": {
                                                    padding: "0px 14px",
                                                },
                                                "& #bookify-all-categories": {
                                                    mt: "0px",
                                                    height: "43px",
                                                    border: "1px solid",
                                                    borderColor: errors.category ? "error.main" : "#BFD4D4",
                                                    display: "flex",
                                                    alignItems: "center"
                                                },
                                            }}
                                        >
                                            <MenuItem value="" disabled>
                                                    {__("Select Category", "bookify")}
                                            </MenuItem>
                                            {AllCategories.map((category, index) => (
                                                <MenuItem key={index} value={category.id}>
                                                    {category.category_name}
                                                </MenuItem>
                                            ))}
                                        </Select>
                                    </FormControl>
                                </Grid>
                                {ProLocation && (
                                    <Grid item xs={12}>
                                        <FormControl fullWidth>
                                            <Typography variant="wpbkThemeLabel" component="label" htmlFor="bookify-all-locations">
                                                {__("Locations", "bookify")}
                                            </Typography>
                                            <Autocomplete
                                                id="bookify-all-locations"
                                                multiple
                                                name="location"
                                                options={allLocations}
                                                getOptionLabel={(location) => location.location_name}
                                                value={currentForm.location}
                                                filterSelectedOptions
                                                onChange={this.handleLocationChange}
                                                renderInput={(params) => (
                                                    <TextField
                                                        {...params}
                                                        sx={{
                                                            border: "1px solid #BFD4D4",
                                                            minHeight: "43px",
                                                            borderRadius: "4px",
                                                            "& .MuiOutlinedInput-root": {
                                                                padding: "0 8px",
                                                                minHeight: "43px",
                                                                borderRadius: "4px",
                                                            },
                                                            "& fieldset": {
                                                                border: "none",
                                                            },
                                                        }}
                                                    />
                                                )}
                                                renderTags={(tagValue, getTagProps) =>
                                                    tagValue.map((option, index) => (
                                                        <Chip
                                                            key={option.id}
                                                            label={option.location_name}
                                                            {...getTagProps({ index })}
                                                        />
                                                    ))
                                                }
                                            />
                                        </FormControl>
                                    </Grid>
                                )}
                                {GoogleConnectBtn && (
                                    <Grid item xs={12}>
                                        <FormControlLabel
                                            disabled={gmeetDisable}
                                            control={<Switch color="primary" />} 
                                            label={(
                                                <Box sx={{display:"flex"}}>
                                                    <Typography variant="wpbkThemeLabel" component="label" sx={{fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen-Sans, Ubuntu, Cantarell, Helvetica Neue, sans-serif"}}>{__( "Enable Google Meet" )}</Typography>
                                                    <Tooltip arrow
                                                        title={
                                                            <React.Fragment>
                                                                {"This service will be available after successful integration with Google Meet. "}<a href="https://wpbookify.com/documentation/integrations/integration-with-google-calendar/" target="_blank" style={{color:"#FFFFFF"}}>{"Click here"}</a>{" for the setup guide."}
                                                            </React.Fragment>
                                                        }
                                                    >
                                                        <InfoIcon sx={{pl:"8px", color:"#000000"}}/>
                                                    </Tooltip>
                                                </Box>
                                            )}
                                            labelPlacement="start" 
                                            name={"toggleGoogleMeet"}
                                            checked={currentForm.toggleGoogleMeet}
                                            onChange={this.handleInputChange}
                                            sx={{
                                                display:"flex", 
                                                justifyContent:"space-between", 
                                                marginLeft:"0px", 
                                                marginRight:"0px",
                                            }}
                                        />
                                    </Grid>
                                )}
                                {ZoomMeeting && (
                                    <Grid item xs={12}>
                                        <FormControlLabel
                                            disabled={zoomDisable}
                                            control={<Switch color="primary" />} 
                                            label={(
                                                <Box sx={{display:"flex"}}>
                                                    <Typography variant="wpbkThemeLabel" component="label" sx={{fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen-Sans, Ubuntu, Cantarell, Helvetica Neue, sans-serif"}}>{__( "Enable Zoom Meeting" )}</Typography>
                                                    <Tooltip arrow
                                                        title={
                                                            <React.Fragment>
                                                                {"This service will be available after successful integration with Zoom. "}<a href="https://wpbookify.com/documentation/integrations/integration-with-zoom/" target="_blank" style={{color:"#FFFFFF"}}>{"Click here"}</a>{" for the setup guide."}
                                                            </React.Fragment>
                                                        }
                                                    >
                                                        <InfoIcon sx={{pl:"8px", color:"#000000"}}/>
                                                    </Tooltip>
                                                </Box>
                                            )}
                                            labelPlacement="start" 
                                            name={"toggleZoomMeeting"}
                                            checked={currentForm.toggleZoomMeeting}
                                            onChange={this.handleInputChange}
                                            sx={{
                                                display:"flex", 
                                                justifyContent:"space-between", 
                                                marginLeft:"0px", 
                                                marginRight:"0px",
                                            }}
                                        />
                                    </Grid>
                                )}
                                <Grid item xs={12}>
                                    <FormControl fullWidth>
                                        <Typography variant="wpbkThemeLabel" component="label" htmlFor="service-note">
                                            {__("Note", "bookify")}
                                        </Typography>
                                        <TextField
                                            id="service-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>
                        
                        </DialogContent>
                        
                        <Divider sx={{borderColor:"#DDEEEE"}} />

                        <DialogActions sx={{m:2}}>
                            <Button variant="wpbkCancelbtn" onClick={this.handleClose}>
                                {__("Cancel", "bookify")}
                            </Button>
                            <LoadingButton variant="wpbkThemeModalBtn" onClick={this.handleServiceSubmit} loading={loading}>
                                {serviceId ? __("Update Service", "bookify") : __("Add Service", "bookify")}
                            </LoadingButton>
                        </DialogActions>
                    </Dialog>
                </ThemeProvider>
                <SnackbarNotice
                    state={this.state}
                    setState={this.setState.bind(this)}
                    open={snackbarOpen}
                    message={snackbarMessage}
                    type={snackbarType}
                />
            </>
        );
    }
}

export default AddService;
