import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { ThemeProvider } from "@mui/material/styles";
import {
    Box, Grid, Accordion, AccordionSummary, Typography,
    AccordionDetails, Checkbox, TextField, FormControlLabel,
    InputAdornment
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import currencies from "../../currencies.json";

class ServiceDetailsForm extends Component {
    state = {
        serviceData: {}
    }

    componentDidMount() {
        const { formData } = this.props;
        if ( formData ) {
            this.setState({ serviceData: this.props.formData });
        }
    }

    handleCheckboxChange = (serviceId, servicePrice, event) => {
        const { checked } = event.target;
        this.setState(prevState => {
            const updatedServiceData = { ...prevState.serviceData };
            if (!updatedServiceData[serviceId]) {
                updatedServiceData[serviceId] = {};
            }

            if (!updatedServiceData[serviceId].price && updatedServiceData[serviceId].price != 0) {
                updatedServiceData[serviceId].price = null;
                updatedServiceData[serviceId].servicePrice = servicePrice;
            }
            updatedServiceData[serviceId].checked = checked;
            this.props.handleServiceData(updatedServiceData);
            return { serviceData: updatedServiceData };
        });
    }

    handleInputChange = (serviceId, servicePrice, event) => {
        const { value } = event.target;
        this.setState((prevState) => {
            const updatedServiceData = { ...prevState.serviceData };
            if (!updatedServiceData[serviceId]) {
                updatedServiceData[serviceId] = {};
            }

            if (value === "") {
                updatedServiceData[serviceId].price = null;
            } else {
                updatedServiceData[serviceId].price = Math.abs(value);
            }
    
            updatedServiceData[serviceId].checked = updatedServiceData[serviceId].checked || false;
            updatedServiceData[serviceId].servicePrice = servicePrice;
            this.props.handleServiceData(updatedServiceData);
            return { serviceData: updatedServiceData };
        });
    };

    render() {
        const { theme, services, currency } = this.props;
        const { serviceData } = this.state;
        const matchedCurrency = Object.values(currencies).find(eachCurrency => eachCurrency.code === currency);

        return (
            <ThemeProvider theme={theme}>
                <Box component="form">
                    <Grid container spacing={2} direction="column">
                        {services.length === 0 ? (
                            <Grid item>
                                <Typography>{__("No service(s) to select!", "bookify")}</Typography>
                            </Grid>
                        ) : (
                            <>  
                                <Grid item>
                                    <Typography variant="wpbkThemeLabel" component="label">
                                        {__("Catgories", "bookify")}
                                    </Typography>
                                </Grid>
                                {services.map((category) => (
                                    <Grid item key={category.id}>
                                        <Accordion defaultExpanded sx={{boxShadow:"none"}}>
                                            <AccordionSummary expandIcon={<ExpandMoreIcon sx={{color:"#036666"}} />}
                                                sx={{
                                                    backgroundColor:"#F8FCFC", 
                                                    borderRadius: "5px",
                                                    border:"1px solid #30AAA7", 
                                                    mt:"5px",
                                                    minHeight: "45px",
                                                    "&.Mui-expanded": {
                                                        minHeight: "45px",
                                                        borderBottomRightRadius: "0px",
                                                        borderBottomLeftRadius: "0px",
                                                    },
                                                    "& .MuiAccordionSummary-content": {
                                                        margin: 0,
                                                        "&.Mui-expanded": {
                                                            margin: 0
                                                        },
                                                    }
                                                }}
                                            >
                                                <Typography sx={{color:"#036666"}}>
                                                    {category.category_name}
                                                </Typography>
                                            </AccordionSummary>
                                            <AccordionDetails 
                                                sx={{
                                                    borderBottomRightRadius:"5px",
                                                    borderBottomLeftRadius:"5px",
                                                    border:"1px solid #30AAA7",
                                                    borderTop: "none",
                                                    padding: "0px"
                                                }}
                                            >
                                                <Grid container sx={{ml:"0px", width:"100%", gap:"10px", p:"16px 0px"}}>
                                                    {category.services.map((service) => (
                                                        <Grid item key={service.id} sx={{width:"100%"}}>
                                                            <Box sx={{p:"0px 16px", display:"flex", justifyContent:"space-between"}}>
                                                                <FormControlLabel
                                                                    control={
                                                                        <Checkbox
                                                                            sx={{
                                                                                color: "#036666",
                                                                                "&.Mui-checked": {
                                                                                    color: "#036666",
                                                                                }
                                                                            }}
                                                                            checked={serviceData[service.id]?.checked || false}
                                                                            onChange={this.handleCheckboxChange.bind(this, service.id, service.service_price)}
                                                                        />
                                                                    }
                                                                    label={
                                                                        <Typography
                                                                            sx={{
                                                                                width: "11rem",
                                                                                textWrap: "nowrap",
                                                                                textOverflow: "ellipsis",
                                                                                overflow: "hidden",
                                                                            }}
                                                                        >
                                                                            {service.service_name}
                                                                        </Typography>
                                                                    }
                                                                />
                                                                <Box sx={{display:"flex", alignItems:"center", gap:"13px"}}>
                                                                    <Typography variant="wpbkThemeLabel" component="label" htmlFor={`service-${service.id}-price`}>
                                                                        {__("Price", "bookify")}
                                                                    </Typography>
                                                                    <TextField
                                                                        id={`service-${service.id}-price`}
                                                                        type="number"
                                                                        name="staffServicePrice"
                                                                        value={
                                                                            serviceData[service.id]?.price === null
                                                                                ? ""
                                                                                : serviceData[service.id]?.price
                                                                        }
                                                                        placeholder={service.service_price}
                                                                        onChange={this.handleInputChange.bind(this, service.id, service.service_price)}
                                                                        InputProps={{
                                                                            startAdornment: (
                                                                                <InputAdornment position="start">
                                                                                    {matchedCurrency.symbol_native}
                                                                                </InputAdornment>
                                                                            ),
                                                                        }}
                                                                        inputProps={{
                                                                            min: 0,
                                                                        }}
                                                                        sx={{
                                                                            width: "10em",
                                                                            border: "1px solid #BFD4D4",
                                                                            height: "43px",
                                                                            borderRadius: "5px",
                                                                            justifyContent: "center",
                                                                            "& fieldset": {
                                                                                border: "none",
                                                                            },
                                                                            "& .MuiOutlinedInput-root": {
                                                                                mt: "0px",
                                                                            },
                                                                            "& input[type=number]::-webkit-outer-spin-button": {
                                                                                WebkitAppearance: "none",
                                                                                margin: 0,
                                                                            },
                                                                            "& input[type=number]::-webkit-inner-spin-button": {
                                                                                WebkitAppearance: "none",
                                                                                margin: 0,
                                                                            },
                                                                        }}
                                                                    />
                                                                </Box>
                                                            </Box>
                                                        </Grid>
                                                    ))}
                                                </Grid>
                                            </AccordionDetails>
                                        </Accordion>
                                    </Grid>
                                ))}
                            </>
                        )}
                    </Grid>
                </Box>
            </ThemeProvider>
        );
    }
}

export default ServiceDetailsForm;
