import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { Box, Grid, Typography, TextField, FormControl, IconButton } from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import RemoveIcon from "@mui/icons-material/Remove";

class ServicesWizard extends Component {
  state = {
    items:
      (this.props.data && this.props.data.services && this.props.data.services.length > 0)
        ? this.props.data.services
        : [{ name: "", price: "" }],
        errors: [{ name: false, price: false }],
    theme: createTheme({
      typography: {
        fontFamily: 'Poppins-Medium, Poppins, sans-serif',
        h3: {
          fontSize: "2em",
          fontWeight: "500",
          textTransform: "capitalize",
          color: "#042626",
        },
        body1: {
          color: "#587373",
          marginTop: "5px",
        },
        wpbkThemeLabel: {
          color: "#042626",
          fontSize: "15px",
          fontWeight: "500",
          paddingBottom: "5px",
        },
      },
      components: {
        MuiTextField: {
          styleOverrides: {
            root: {
              border: "1px solid #57b0ee",
              height: "43px",
              borderRadius: "5px",
              justifyContent: "center",
              marginTop: "5px",
              "& fieldset": {
                border: "none",
              },
              "& .MuiOutlinedInput-root": {
                mt: "0px",
                border: "none",
              },
              "& .MuiInputBase-input": {
                fontSize: "12px",
                padding: "5px 14px 5px",
                border: "transparent",
                minHeight: "28px",
              },
              "& .MuiOutlinedInput-input:focus": {
                boxShadow: "none",
              },
            },
          },
        },
        MuiIconButton: {
          styleOverrides: {
            root: {
              border: "1px solid #57b0ee",
              borderRadius: "8px",
              marginTop: "27px",
              marginLeft: "8px",
              color: "#000000ff",
              height: "43px",
              "&:hover": { backgroundColor: "#f3f4f6" },
            },
          },
        },
      },
    }),
  };

  componentDidMount() {
    this.props.saveStep("services", this.state.items);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.items !== this.state.items) {
      this.props.saveStep("services", this.state.items);
    }
  }

  handleUpdate = (i, key, value) => {
    const next = this.state.items.map((s, idx) =>
      idx === i ? { ...s, [key]: value } : s
    );
    this.setState({ items: next });
  };

  handleAdd = () => {
    this.setState({
      items: [...this.state.items, { name: "", price: "" }],
      errors: [...this.state.errors, { name: false, price: false }]
    });
  };

  handleRemove = (i) => {
    if (this.state.items.length > 1) {
      this.setState({
        items: this.state.items.filter((_, idx) => idx !== i),
      });
    }
  };

  validate = () => {
    const errors = this.state.items.map(item => ({
      name: !item.name.trim(),
      price: !item.price || item.price.trim() === ""
    }));
    this.setState({ errors });
    return !errors.some(e => e.name || e.price);
  };

  render() {
    const { theme, items, errors } = this.state;

    if (this.props.onValidate) {
      this.props.onValidate(this.validate);
    }

    return (
      <ThemeProvider theme={theme}>
        <Box component="div" sx={{ mb: "4em" }}>
          <Typography variant="h3">{__("Services", "apbgf")}</Typography>
          <Typography variant="body1" sx={{ mt: 1 }}>
            {__("Manage services you're offering", "apbgf")}
          </Typography>
        </Box>

        <Box component="form">
          {items && items.length > 0 ? (
            items.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">
                    {__("Service Name", "apbgf")} <span style={{ color: '#d32f2f' }}>*</span>
                  </Typography>
                  <TextField
                    fullWidth
                    placeholder={__("Hair styling, dental checkup etc.", "apbgf")}
                    value={s.name || ""}
                    onChange={(e) => this.handleUpdate(idx, "name", e.target.value)}
                    error={errors[idx]?.name}
                    sx={{
                        border: errors[idx]?.name ? '1px solid #d32f2f' : '1px solid #57b0ee',
                    }}
                  />
                  {errors[idx]?.name && (
                      <Typography sx={{ color: '#d32f2f', fontSize: '0.75rem', mt: 0.5 }}>
                          {__("This field is required.", "apbgf")}
                      </Typography>
                  )}
                  </FormControl>
                </Grid>

                <Grid item xs={12} md={4}>
                  <FormControl fullWidth>
                    <Typography variant="wpbkThemeLabel" component="label">
                      {__("Set Price", "apbgf")} <span style={{ color: '#d32f2f' }}>*</span>
                    </Typography>
                    <TextField
                      fullWidth
                      type="number"
                      value={s.price || ""}
                      inputProps={{ min: 0 }}
                      onChange={(e) => {
                        const raw = e.target.value;
                        const next = raw === "" ? "" : String(Math.max(0, Number(raw)));
                        this.handleUpdate(idx, "price", next);
                      }}
                      error={errors[idx]?.name}
                    sx={{
                        border: errors[idx]?.name ? '1px solid #d32f2f' : '1px solid #57b0ee',
                    }}
                    />
                    {errors[idx]?.name && (
                        <Typography sx={{ color: '#d32f2f', fontSize: '0.75rem', mt: 0.5 }}>
                            {__("This field is required.", "apbgf")}
                        </Typography>
                    )}
                  </FormControl>
                </Grid>

                <Grid item xs={12} md={2}>
                  <IconButton
                    onClick={() =>
                      idx === items.length - 1
                        ? this.handleAdd()
                        : this.handleRemove(idx)
                    }
                  >
                    {idx === items.length - 1 ? <AddIcon /> : <RemoveIcon />}
                  </IconButton>
                </Grid>
              </Grid>
            ))
          ) : (
            <Grid container spacing={2} alignItems="center" sx={{ mb: 2 }}>
              <Grid item xs={12} md={6}>
                <FormControl fullWidth>
                  <Typography variant="wpbkThemeLabel" component="label">
                    {__("Service Name", "apbgf")}
                  </Typography>
                  <TextField
                    fullWidth
                    placeholder={__("Hair styling, dental checkup etc.", "apbgf")}
                    value=""
                    onChange={(e) =>
                      this.setState({ items: [{ name: e.target.value, price: "" }] })
                    }
                  />
                </FormControl>
              </Grid>

              <Grid item xs={12} md={4}>
                <FormControl fullWidth>
                  <Typography variant="wpbkThemeLabel" component="label">
                    {__("Set Price", "apbgf")}
                  </Typography>
                  <TextField
                    fullWidth
                    type="number"
                    placeholder={"$"}
                    value=""
                    onChange={(e) =>
                      this.setState({ items: [{ name: "", price: e.target.value }] })
                    }
                  />
                </FormControl>
              </Grid>

              <Grid item xs={12} md={2}>
                <IconButton onClick={this.handleAdd}>
                  <AddIcon />
                </IconButton>
              </Grid>
            </Grid>
          )}
        </Box>
      </ThemeProvider>
    );
  }
}

export default ServicesWizard;