import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { Box, Button, Checkbox, Chip, FormControl, FormControlLabel, Grid, IconButton, MenuItem, OutlinedInput, Select, Typography } from "@mui/material";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { TimePicker } from "@mui/x-date-pickers/TimePicker";
import DeleteIcon from "@mui/icons-material/Delete";
import dayjs from "dayjs";

class StaffWizard 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",
                }
            }
        }),
    };

    handleCheckboxChange = (day) => (event) => {
        const { state, setState } = this.props;
        const { checked } = event.target;
        const scheduleItem = state.schedule[day];
        setState((prev) => ({
          schedule: {
            ...prev.schedule,
            [day]: {
              ...scheduleItem,
              checked,
              fromError: checked && (!scheduleItem.from || scheduleItem.from === ""),
              toError: checked && (!scheduleItem.to || scheduleItem.to === ""),
            },
          },
        }));
    };

    handleTimeChange = (day, field) => (newValue) => {
        const { state, setState } = this.props;
        const isChecked = state.schedule[day]?.checked;
        setState((prev) => ({
            schedule: {
                ...prev.schedule,
                [day]: {
                    ...prev.schedule[day],
                    [field]: newValue,
                    [`${field}Error`]: isChecked && !newValue,
                },
            },
        }));
    };

    handleAddBreak = (day) => {
        const { setState } = this.props;
        setState((prev) => ({ 
            schedule: { 
                ...prev.schedule, 
                [day]: { 
                    ...prev.schedule[day], breaks: [] 
                } 
            } 
        }));
    };

    handleDeleteBreak = (day) => {
        const { setState } = this.props;
        setState((prev) => ({ 
            schedule: { 
                ...prev.schedule, 
                [day]: { 
                    ...prev.schedule[day], breaks: null 
                } 
            } 
        }));
    };
        
    handleBreakChange = (day) => (event) => {
        const { setState } = this.props;
        setState((prev) => ({ 
            schedule: { 
                ...prev.schedule, 
                [day]: { 
                    ...prev.schedule[day], breaks: event.target.value 
                } 
            } 
        })); 
    };

    convertHours = (time) => {
        const { state } = this.props;
        const timeFormat = state.general.DefaultTimeFormat === "12-hour" ? "hh:mm A" : "HH:mm";
        return dayjs().startOf("day").add(time, "minute").format(timeFormat);
      };

    BookifySplitTime = (start_time, end_time) => {
        const { state } = this.props;
        let duration = parseInt(state.general.DefaultGlobalSlotTimeDuration || "30");
        let interval = parseInt(state.general.DefaultGlobalSlotTimeInterval || "15");
        let time_slots = [];
        let start = start_time.hour() * 60 + start_time.minute();
        let end = end_time.hour() * 60 + end_time.minute();
        while (start + interval < end) {
          let slot_start = start;
          let slot_end = slot_start + duration;
          time_slots.push(`${this.convertHours(slot_start)} - ${this.convertHours(slot_end)}`);
          start = slot_end + interval;
        }
        return time_slots;
      };
        

    renderDayRow(day, timeFormat, ampm) {
        const { state } = this.props;

        return (
            <Grid
                container
                spacing={2}
                direction="row"
                justifyContent="space-between"
                alignItems="center"
                sx={{
                    border: "1px solid #DDEEEE",
                    borderRadius: "5px",
                    padding: "15px 10px",
                    mt: "10px",
                    fontFamily: "Figtree, sans-serif",
                    width: "100%",
                }}
                key={day}
            >
                <Grid item md={2} sx={{ pl: "unset !important", pt: "unset !important" }}>
                    <FormControlLabel
                        control={
                            <Checkbox
                                sx={{ color: "#036666", "&.Mui-checked": { color: "#036666" } }}
                                checked={state.schedule[day].checked}
                                onChange={this.handleCheckboxChange(day)}
                                name={day}
                            />
                        }
                        label={day.charAt(0).toUpperCase() + day.slice(1)}
                        sx={{".MuiFormControlLabel-label": { color: "#111827" }}}
                    />
                </Grid>

                <Grid item md={2.5} sx={{ pl: "unset !important", pt: "unset !important" }}>
                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                        <TimePicker
                            label="From"
                            format={timeFormat}
                            views={["hours", "minutes"]}
                            ampm={ampm}
                            timeSteps={{ hours: 1, minutes: 1 }}
                            value={state.schedule[day].from}
                            onChange={this.handleTimeChange(day, "from")}
                            slotProps={{
                                textField: { error: state.schedule[day].fromError },
                                popper: { disablePortal: false, style: { zIndex: 1000002 } }
                            }}
                            sx={{
                                width: "100%",
                                "& input[type=text]": { padding: "7px 10px" },
                                "& label": {
                                    fontSize: "13px",
                                    lineHeight: "6px",
                                    overflow: "unset",
                                    color: "#587373",
                                    zIndex: "9999"
                                },
                                "& label.MuiInputLabel-shrink": { lineHeight: "25px", zIndex: "9999" },
                                "& svg": { width: "18px", height: "18px", color: "#587373" },
                                "& fieldset": {
                                    borderColor: state.schedule[day].fromError ? "error.main" : "#BFD4D4"
                                },
                                "& .MuiInputBase-root:hover fieldset": {
                                    borderColor: state.schedule[day].fromError ? "error.main" : "#BFD4D4"
                                },
                                "& .MuiInputBase-root.Mui-focused fieldset": { borderWidth: "1px" }
                            }}
                        />
                    </LocalizationProvider>
                </Grid>

                <Grid item md={2.5} sx={{ pl: "unset !important", pt: "unset !important" }}>
                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                        <TimePicker
                            label="To"
                            format={timeFormat}
                            views={["hours", "minutes"]}
                            ampm={ampm}
                            timeSteps={{ hours: 1, minutes: 1 }}
                            value={state.schedule[day].to}
                            onChange={this.handleTimeChange(day, "to")}
                            slotProps={{
                                textField: { error: state.schedule[day].toError },
                                popper: { disablePortal: false, style: { zIndex: 1000002 } }
                            }}
                            sx={{
                                width: "100%",
                                "& input[type=text]": { padding: "7px 10px" },
                                "& label": {
                                    fontSize: "13px",
                                    lineHeight: "6px",
                                    overflow: "unset",
                                    color: "#587373",
                                    zIndex: "9999"
                                },
                                "& label.MuiInputLabel-shrink": { lineHeight: "25px", zIndex: "9999" },
                                "& svg": { width: "18px", height: "18px", color: "#587373" },
                                "& fieldset": {
                                    borderColor: state.schedule[day].toError ? "error.main" : "#BFD4D4"
                                },
                                "& .MuiInputBase-root:hover fieldset": {
                                    borderColor: state.schedule[day].toError ? "error.main" : "#BFD4D4"
                                },
                                "& .MuiInputBase-root.Mui-focused fieldset": { borderWidth: "1px" }
                            }}
                        />
                    </LocalizationProvider>
                </Grid>

                <Grid
                    item
                    md={3}
                    sx={{
                        pl: "unset !important",
                        pt: "unset !important",
                        display: "flex",
                        flexDirection: "column",
                        alignItems: "center"
                    }}
                >
                    {state.schedule[day].breaks === null && (
                        <Button
                            variant="contained"
                            onClick={() => this.handleAddBreak(day)}
                            sx={{
                                boxShadow: "none",
                                backgroundColor: "#EBF8F8",
                                color: "#036666",
                                fontSize:"0.875rem",
                                "&:hover": { backgroundColor: "#DAEFEF", boxShadow: "none" }
                            }}
                        >
                            <Typography sx={{lineHeight:"24px", textTransform:"capitalize"}}>
                                {__("Add Break", "bookify")}
                            </Typography>
                        </Button>
                    )}

                    {state.schedule[day].breaks !== null && (
                        <Grid container spacing={1} sx={{ alignItems: "center", justifyContent: "center" }}>
                            <Grid item xs={8}>
                                <FormControl sx={{ width: "100%" }}>
                                    <Select
                                        multiple
                                        displayEmpty
                                        value={state.schedule[day].breaks}
                                        onChange={this.handleBreakChange(day)}
                                        input={<OutlinedInput />}
                                        MenuProps={{ disablePortal: false, style: { zIndex: 1000001 } }}
                                        renderValue={(selected) => {
                                            if (selected.length === 0) {
                                                return (
                                                    <span style={{ color: "#587373" }}>
                                                        {__("Select Break Duration", "bookify")}
                                                    </span>
                                                );
                                            }
                                            return (
                                                <Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.5 }}>
                                                    {selected.map((value) => (
                                                        <Chip key={value} label={value} size="small" />
                                                    ))}
                                                </Box>
                                            );
                                        }}
                                        sx={{
                                            "& .MuiOutlinedInput-input": { padding: "7px 10px" },
                                            "& fieldset": { borderColor: "#BFD4D4" },
                                            "&.MuiInputBase-root:hover fieldset": { borderColor: "#BFD4D4" }
                                        }}
                                    >
                                        {(() => {
                                            const { from, to } = state.schedule[day];
                                            const slots = from && to ? this.BookifySplitTime(from, to) : [];
                                            return slots.map((value) => (
                                                <MenuItem key={value} value={value}>
                                                    {value}
                                                </MenuItem>
                                            ));
                                        })()}
                                    </Select>
                                </FormControl>
                            </Grid>
                            <Grid item xs={4} sx={{ display: "flex", justifyContent: "center" }}>
                                <IconButton
                                    color="error"
                                    onClick={() => this.handleDeleteBreak(day)}
                                    sx={{
                                        border: "1px solid #f44336",
                                        borderRadius: "8px",
                                        width: "36px",
                                        height: "36px"
                                    }}
                                >
                                    <DeleteIcon sx={{ fontSize: "18px" }} />
                                </IconButton>
                            </Grid>
                        </Grid>
                    )}
                </Grid>
            </Grid>
        );
    }

    render() {
        const { state } = this.props;
        const { theme } = this.state;
        const timeFormat = state.general.DefaultTimeFormat === "12-hour" ? "hh:mm A" : "HH:mm";
        const ampm = state.general.DefaultTimeFormat === "12-hour";

        return (
            <ThemeProvider theme={theme}>
                <Box component="div" sx={{mb:"2em"}}>
                    <Typography variant="h2">
                        {__("Staff Details", "bookify")}
                    </Typography>
                    <Typography variant="body1">
                        {__("Set the Working Hours (Default 09:00 AM – 05:00 PM).", "bookify")}
                    </Typography>
                </Box>

                <Box component="form">
                    {Object.keys(state.schedule).map((day) => this.renderDayRow(day, timeFormat, ampm))}
                </Box>
            </ThemeProvider>
        );
    }
}

export default StaffWizard;