import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { 
    Dialog, DialogTitle, DialogContent, DialogActions,
    Divider, IconButton, Button
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import {SnackbarNotice} from "../../functions";
import AppointmentFields from "./AppointmentFields";
import LoadingButton from "@mui/lab/LoadingButton";

class AddAppointment extends Component { 

    state = { 
        servicePrice: "",
        formData: {
            appointmentLocation: "",
            appointmentService: "",
            appointmentStaff: "",
            appointmentDate: null,
            appointmentDuration: [],
            appointmentCustomer: "",
            appointmentStatus: "",
            appointmentNote: "",
        },
        errors: {
            appointmentLocation: false,
            appointmentStaff: false,
            appointmentService: false,
            appointmentDate: false,
            appointmentDuration: false,
            appointmentStatus: false,
            appointmentCustomer: false,
        },
        snackbarOpen: false,
        snackbarMessage: "",
        snackbarType: "",
        loading: false,
        loadingData: 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"
                        },
                    },
                },
            }
        })
    };

    handleClose = () => {
        this.setState({
          formData: {
            appointmentLocation: "",
            appointmentService: "",
            appointmentStaff: "",
            appointmentDate: null,
            appointmentDuration: [],
            appointmentCustomer: "",
            appointmentNote: "",
          }
        }, () => {
          this.props.onClose && this.props.onClose();
        });
    };


    AddAppointmentDetails = () => {
        const { formData, servicePrice } = this.state;
        const { fetchAppointmentData } = this.props;
        
        const ProLocation = window.ProLocation;

        const errors = {
            appointmentLocation: formData.appointmentLocation === "" || !formData.appointmentLocation,
            appointmentService: formData.appointmentService === "" || !formData.appointmentService,
            appointmentStaff: formData.appointmentStaff === "" || !formData.appointmentStaff,
            appointmentDate: !formData.appointmentDate,
            appointmentDuration: formData.appointmentDuration.length === 0 || !formData.appointmentDuration,
            appointmentStatus: !formData.appointmentStatus,
            appointmentCustomer: formData.appointmentCustomer === "" || !formData.appointmentCustomer,
        };
    
        this.setState({ errors });
    
        if ( errors.appointmentService || errors.appointmentStaff || errors.appointmentDate || errors.appointmentDuration || errors.appointmentCustomer || errors.appointmentStatus ) {
            return;
        }

        if ( ProLocation && errors.appointmentLocation ) {
            return;
        }

        const totalPrice = servicePrice * ( typeof formData.appointmentDuration == "string" ? 1 : formData.appointmentDuration.length );

        this.setState({ loading: true });
    
        const dataToSend = {};
        if ( ProLocation ) {
            dataToSend.appointment_location = formData.appointmentLocation;
        }
        dataToSend.appointment_service = formData.appointmentService;
        dataToSend.appointment_staff = formData.appointmentStaff;
        dataToSend.appointment_date = formData.appointmentDate ? formData.appointmentDate.format( "YYYY-MM-DD" ) : "";
        dataToSend.appointment_duration = Array.isArray(formData.appointmentDuration) ? formData.appointmentDuration.join(',') : formData.appointmentDuration;
        dataToSend.appointment_price = totalPrice;
        dataToSend.customer_id = formData.appointmentCustomer;
        dataToSend.appointment_status = formData.appointmentStatus;
        dataToSend.note = formData.appointmentNote;

        fetch(`${wpbAdmin.root}bookify/v1/add-appointment`, {
            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({ 
                    snackbarOpen: true,
                    snackbarMessage: response.message,
                    snackbarType: "success",
                    loading: false
                });
                this.handleClose();
            } else {
                this.setState({ 
                    snackbarOpen: true, 
                    snackbarMessage: response.message, 
                    snackbarType:  "error",
                    loading: false
                });
            }
            fetchAppointmentData();
        })
        .catch(error => {
            console.error("Error:", error);
            this.setState({ loading: false });
        })
    };

    render() { 
        const { open, locations, services, customers, dateFormat, priorToggle, priorTime, DefaultAppointmentStatus } = this.props;
        const { theme, formData, errors, snackbarOpen, snackbarMessage, snackbarType, loading, loadingData } = this.state;
        formData.appointmentStatus = formData.appointmentStatus ? formData.appointmentStatus : DefaultAppointmentStatus;

        return (
            <>  
                <ThemeProvider theme={theme}>
                    <Dialog onClose={this.handleClose} open={open} fullWidth={true} maxWidth={"sm"} sx={{height:"80%", padding:"4% 0%"}}>
                        <DialogTitle sx={{ display: "flex", alignItems: "center" }}>
                            {__("Add Appointment", "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>
                            <AppointmentFields
                                state={this.state}
                                setState={this.setState.bind(this)}
                                formData={formData}
                                errors={errors}
                                locations={locations}
                                services={services}
                                customers={customers}
                                dateFormat={dateFormat}
                                priorToggle={priorToggle}
                                priorTime={priorTime}
                                loadingData={loadingData}
                                theme={theme}
                            />
                        </DialogContent>
                        
                        <Divider sx={{borderColor:"#DDEEEE"}} />

                        <DialogActions sx={{m:2}}>
                            <Button variant="wpbkCancelbtn" onClick={this.handleClose}>
                                {__("Cancel", "bookify")}
                            </Button>
                            <LoadingButton variant="wpbkThemeModalBtn" onClick={this.AddAppointmentDetails} loading={loading}>
                                {__("Schedule", "bookify")}
                            </LoadingButton>
                        </DialogActions>
                    </Dialog>
                </ThemeProvider>
                <SnackbarNotice
                    state={this.state}
                    setState={this.setState.bind(this)}
                    open={snackbarOpen}
                    message={snackbarMessage}
                    type={snackbarType}
                />
            </>
        );
    }
}

export default AddAppointment;
