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

class EditAppointment extends Component { 
    state = {
        TabValue: "AppointmentDetails",
        servicePrice: "",
        formData: {
            appointmentID: "",
            appointmentLocation: "",
            appointmentService: "",
            appointmentStaff: "",
            appointmentDate: null,
            appointmentDuration: [],
            appointmentCustomer: "",
            appointmentStatus: "",
            appointmentNote: "",
        },
        errors: {
            appointmentLocation: false,
            appointmentService: false,
            appointmentStaff: false,
            appointmentDate: false,
            appointmentDuration: false,
            appointmentStatus: false,
            appointmentCustomer: false,
        },
        snackbarOpen: false,
        snackbarMessage: "",
        snackbarType: "success",
        loading: false,
        loadingData: true,
        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",
                                },
                            }
                        }
                    ]
                },
                MuiTabs: {
                    styleOverrides: {
                        root: {
                            minHeight: "0px",
                            "& .MuiTabs-indicator": {
                                backgroundColor: "#036666"
                            },
                            "& .MuiTabs-flexContainer": {
                                borderBottom: "2px solid #DDEEEE",
                                justifyContent: "flex-start",
                            }
                        }
                    }
                },
                MuiTab: {
                    styleOverrides: {
                        root: {
                            textTransform: "capitalize",
                            fontSize: "16px",
                            fontWeight: 600,
                            color: "#587373",
                            padding: "16px 14px",
                            minHeight: "0px",
                            "&.Mui-selected": {
                                color: "#036666"
                            }
                        }
                    }
                },
                MuiMenuItem: {
                    styleOverrides: {
                        root: {
                            marginLeft: "3px",
                            marginRight: "3px",
                            paddingLeft: "10px",
                            paddingRight: "10px",
                            borderRadius: "8px"
                        },
                    },
                },
                MuiChip: {
                    variants: [
                        {
                            props: { variant: "deletebtn" },
                            style: {
                                borderColor: "none",
                                borderRadius: "4px",
                                backgroundColor: "#FFEDED",
                                color: "#C9605C",
                                textTransform: "capitalize",
                                height: "35px",
                                "&:hover": {
                                    backgroundColor: "#FFDFDF",
                                    color: "#C9605C"
                                },
                                "&:active": {
                                    boxShadow: "unset"
                                }
                            },
                        },
                    ],
                }
            }
        })
    }

    componentDidUpdate(prevProps) {
        const { editFormData } = this.props;
        if (editFormData && editFormData !== prevProps.editFormData) {
            this.setState({
                formData: {
                    appointmentID: editFormData.appointment_id,
                    appointmentLocation: editFormData.appointment_location || "",
                    appointmentService: editFormData.service_id || "",
                    appointmentStaff: editFormData.appointment_staff || "",
                    appointmentDate: dayjs(editFormData.appointment_date) || null,
                    appointmentDuration: JSON.parse( editFormData.appointment_duration ) || "",
                    appointmentCustomer: editFormData.appointment_customer || "",
                    appointmentStatus: editFormData.appointment_status || "",
                    appointmentNote: editFormData.appointment_note || "",
                }
            });
        } else if ( ! editFormData && prevProps.editFormData ) {
            this.setState({
                formData: {
                    appointmentLocation: "",
                    appointmentService: "",
                    appointmentStaff: "",
                    appointmentDate: null,
                    appointmentDuration: [],
                    appointmentCustomer: "",
                    appointmentStatus: "",
                    appointmentNote: "",
                }
            });
        }
    }

    handleClose = () => { 
        this.setState({
            loadingData: true
        }, () => {
            this.props.onClose && this.props.onClose();
        });
    };

    handleTabChange = (event, newValue) => {
        this.setState({
            TabValue: newValue,
        });
    };

    EditAppointmentDetails = () => {
        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.appointmentStaff || errors.appointmentService || 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_id = formData.appointmentID;
        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/update-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();
                fetchAppointmentData();
            } else {
                this.setState({ 
                    snackbarOpen: true, 
                    snackbarMessage: response.message, 
                    snackbarType:  "error",
                    loading: false,
                });
            }
        })
        .catch(error => {
            console.error("Error:", error);
            this.setState({ loading: false });
        })
    };

    render() {
        const { open, locations, services, customers, priorToggle, priorTime, dateFormat, timeFormat, currency, editFormData } = this.props;
        const { theme, TabValue, errors, snackbarOpen, snackbarMessage, snackbarType, formData, loading, loadingData } = this.state;
        
        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" }}>
                            {__("Edit 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>
                            <TabContext value={TabValue}>
                                <TabList onChange={this.handleTabChange}>
                                    <Tab value="AppointmentDetails" label={__("Appointment Details", "bookify")} />
                                    <Tab value="PaymentDetails" label={__("Payment Details", "bookify")}/>
                                </TabList>
                                
                                <TabPanel value="AppointmentDetails" sx={{pt:"24px", pb:"24px", pl:"0px", pr:"0px"}}>
                                    <AppointmentFields
                                        state={this.state}
                                        setState={this.setState.bind(this)}
                                        formData={formData}
                                        errors={errors}
                                        locations={locations}
                                        services={services}
                                        customers={customers}
                                        dateFormat={dateFormat}
                                        timeFormat={timeFormat}
                                        priorToggle={priorToggle}
                                        priorTime={priorTime}
                                        loadingData={loadingData}
                                        theme={theme}
                                    />
                                </TabPanel>

                                <TabPanel value="PaymentDetails" sx={{pt:"24px", pb:"24px", pl:"0px", pr:"0px"}}>
                                    <PaymentDetails
                                        state={this.state}
                                        setState={this.setState.bind(this)}
                                        editFormData={editFormData}
                                        currency={currency}
                                        theme={theme}
                                    />
                                </TabPanel>
                            </TabContext>
                        </DialogContent>

                    { TabValue && "AppointmentDetails" == TabValue && (
                        <>
                            <Divider sx={{borderColor:"#DDEEEE"}} />

                            <DialogActions sx={{m:2}}>
                                <Button variant="wpbkCancelbtn" onClick={this.handleClose}>
                                    {__("Cancel", "bookify")}
                                </Button>
                                <LoadingButton variant="wpbkThemeModalBtn" onClick={this.EditAppointmentDetails} loading={loading}>
                                    {__("Update Schedule", "bookify")}
                                </LoadingButton>

                            </DialogActions>
                        </>
                    )}
                    
                    </Dialog>
                </ThemeProvider>
                <SnackbarNotice
                    state={this.state}
                    setState={this.setState.bind(this)}
                    open={snackbarOpen}
                    message={snackbarMessage}
                    type={snackbarType}
                />
            </>
        )
    }
}

export default EditAppointment;
