import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { Box, Grid, TextField, Typography, IconButton, FormControl, InputAdornment } from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import RemoveIcon from "@mui/icons-material/Remove";

class ServicesWizard extends Component {
    state = {
        theme: createTheme({
            typography: {
                h2: {
                    fontSize: "1.5rem",
                    fontWeight: "550",
                    lineHeight: "2rem",
                    textTransform: "capitalize",
                    color: "#111827",
                },
                body1: {
                    fontFamily: "Figtree, sans-serif",
                    fontSize: "0.875rem",
                    lineHeight: "1.25rem",
                    color: "#4b5563",
                    marginTop: "4px"
                },
                wpbkThemeLabel: {
                    color: "#111827",
                    fontFamily: "Figtree, sans-serif",
                    fontSize: "0.875rem",
                    fontWeight: "500",
                    lineHeight: "1.25rem",
                }
            },
            components: {
                MuiTextField: {
                    styleOverrides: {
                        root: {
                            height: "43px",
                            borderRadius: "5px",
                            justifyContent: "center",
                            marginTop: "5px",
                            "& fieldset": {
                                border: "none",
                            },
                            "& .MuiOutlinedInput-root": {
                                mt: "0px",
                            },
                            "& .MuiInputBase-input": {
                                padding: "0px 14px 5px"
                            }
                        }
                    }
                },
                MuiIconButton: {
                    styleOverrides: {
                        root: {
                            border: "1px solid #d1d5db",
                            borderRadius: "8px",
                            marginTop: "27px",
                            marginLeft: "8px",
                            color: "#036666",
                            height: "43px",
                            "&:hover": { backgroundColor: "#f3f4f6" }
                        }
                    }
                }
            },
        }),
        errors: []
    };

    handleAddService = () => {
        const { setState } = this.props;
        setState(prev => ({
            services: [
                ...prev.services,
                { name: "", price: "", category: "uncategorized" }
            ]
        }));
    };

    handleRemoveService = (idx) => {
        const { setState } = this.props;
        setState((prev) => ({
            services: prev.services.filter((_, i) => i !== idx)
        }));
    }

    handleUpdateService = (idx, event) => {
        const { setState } = this.props;
        const { name, value } = event.target;
        setState((prev) => ({
            services: prev.services.map((s, i) => (i === idx ? { ...s, [name]: value } : s)),
        }));

        this.setState((prevState) => {
            const newErrors = [...(prevState.errors || [])];
            if (!newErrors[idx]) newErrors[idx] = { name: false, price: false };
            if (name === "name") {
                newErrors[idx].name = !value || value.trim() === "";
            }
            if (name === "price") {
                newErrors[idx].price = !value || String(value).trim() === "";
            }
            return { errors: newErrors };
        });
    }

    validate = () => {
        const { state } = this.props;
        const errors = state.services.map((s) => ({
            name: !s.name || s.name.trim() === "",
            price: !s.price || String(s.price).trim() === ""
        }));
        this.setState({ errors });
        return errors.every(e => !e.name && !e.price);
    };

    componentDidMount() {
        if (this.props.setValidate) {
            this.props.setValidate(this.validate);
        }
    }

    render() {
        const { theme, errors } = this.state;
        const { state, currencySymbol } = this.props;

        return (
            <ThemeProvider theme={theme}>
                <Box component="div" sx={{ mb: "2em" }}>
                    <Typography variant="h2">
                        {__("Services", "bookify")}
                    </Typography>
                    <Typography variant="body1">
                        {__("Manage Services You're Offering", "bookify")}
                    </Typography>
                </Box>

                <Box component="form">
                    {state.services.map((s, idx) => (
                        <Grid
                            container
                            spacing={2}
                            alignItems="center"
                            key={idx}
                            sx={{ mb: 2 }}
                        >
                            <Grid item xs={12} md={6}>
                                <FormControl fullWidth>
                                    <Typography variant="wpbkThemeLabel" component="label" htmlFor={`wiz-service-name-${idx}`}>
                                        {__("Service Name ", "bookify")}
                                        <span style={{ color: "#DC2626" }}>*</span>
                                    </Typography>
                                    <TextField
                                        id={`wiz-service-name-${idx}`}
                                        required
                                        type="text"
                                        name="name"
                                        value={s.name}
                                        onChange={(e) => this.handleUpdateService(idx, e)}
                                        error={errors && errors[idx] && errors[idx].name}
                                        sx={{
                                            borderRadius: "5px",
                                            justifyContent: "center",
                                            "& fieldset": {
                                                border: "none",
                                            },
                                            "& .MuiOutlinedInput-root": {
                                                mt: "0px",
                                                height: "43px",
                                                border: "1px solid",
                                                borderColor: errors && errors[idx] && errors[idx].name ? "error.main" : "#BFD4D4",
                                            },
                                            "& .MuiInputBase-input": {
                                                padding: "0px 14px"
                                            }
                                        }}
                                    />
                                </FormControl>
                            </Grid>

                            <Grid item xs={12} md={4}>
                                <FormControl fullWidth>
                                    <Typography variant="wpbkThemeLabel" component="label" htmlFor={`wiz-service-price-${idx}`}>
                                        {__("Price ", "bookify")}
                                        <span style={{ color: "#DC2626" }}>*</span>
                                    </Typography>
                                    <TextField
                                        id={`wiz-service-price-${idx}`}
                                        required
                                        type="number"
                                        name="price"
                                        value={s.price}
                                        onChange={(e) => this.handleUpdateService(idx, e)}
                                        error={errors && errors[idx] && errors[idx].price}
                                        InputProps={{
                                            startAdornment: (
                                                <InputAdornment position="start" sx={{ "& .MuiTypography-root": { mt: 0 } }}>
                                                    {currencySymbol || "$"}
                                                </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": {
                                                p: "0px"
                                            },
                                            "& .MuiOutlinedInput-root": {
                                                mt: "0px",
                                                height: "43px",
                                                border: "1px solid",
                                                borderColor: errors && errors[idx] && errors[idx].price ? "error.main" : "#BFD4D4",
                                            },
                                            "& fieldset": {
                                                border: "none",
                                            },
                                        }}
                                    />
                                </FormControl>
                            </Grid>

                            <Grid item xs={12} md={2}>
                                <IconButton
                                    onClick={() => {
                                        if (idx === 0) {
                                            this.handleAddService();
                                        } else {
                                            this.handleRemoveService(idx);
                                        }
                                    }}
                                >
                                    {idx === 0 ? <AddIcon /> : <RemoveIcon />}
                                </IconButton>
                            </Grid>
                        </Grid>
                    ))}
                </Box>
            </ThemeProvider>
        );
    }
}

export default ServicesWizard;