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 StaffDetailsForm from "./StaffDetails";
import ServiceDetailsForm from "./ServiceDetails";
import ScheduleDetailsForm from "./ScheduleDetails";
import SpecialDayDetailsForm from "./SpecialDayDetails";
import HolidayDetailsForm from "./HolidayDetails";
import { SnackbarNotice } from "../../functions";
import dayjs from "dayjs";
import LoadingButton from "@mui/lab/LoadingButton";

class AddStaff extends Component { 

    state = {
        addFormData: {
            fullName: "",
            profession: "",
            email: "",
            password: "",
            phoneNumber: "",
            note: "",
            image: "",
            serviceData: "",
            slotDuration: "",
            slotInterval: "",
            staffMultipleBooking: "false",
            scheduleData: "",
            specialDayData: "",
            holidayData: "",
        },
        editFormData: {
            fullName: "",
            profession: "",
            email: "",
            password: "",
            phoneNumber: "",
            note: "",
            image: "",
            serviceData: "",
            slotDuration: "",
            slotInterval: "",
            staffMultipleBooking: "false",
            scheduleData: "",
            specialDayData: "",
            holidayData: "",
            googleConnection: false,
            outlookConnection: false,
            zoomUserId: "",
        },
        errors: { 
            fullName: false,
            email: false,
            emailValidation: false,
            password: false,
            phoneNumber: false,
        },
        TabValue: "staffDetails",
        staffRegistered: false,
        staffRegisteredId: false,
        snackbarOpen: false,
        snackbarMessage: "",
        snackbarType: "success",
        loading: 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",
                                },
                            }
                        }
                    ],
                },
                MuiTabs: {
                    styleOverrides: {
                        root: {
                            minHeight: "0px",
                            "& .MuiTabs-indicator": {
                                backgroundColor: "#036666"
                            },
                            "& .MuiTabs-flexContainer": {
                                borderBottom: "2px solid #DDEEEE",
                                justifyContent: "space-between",
                            }
                        }
                    }
                },
                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"
                        },
                    },
                },
                MuiSwitch: {
                    styleOverrides: {
                        root: {
                            width: "40px",
                            height: "23px",
                            padding: "0px",
                            borderRadius: "13px"
                        },
                        switchBase: {
                            padding: "0px",
                            margin: "3px",
                            transitionDuration: "300ms",
                            "&.Mui-checked": {
                                transform: "translateX(17px)",
                                color: "#FFFFFF",
                                "& .MuiSwitch-thumb": {
                                    color: "#EBF8F8",
                                },
                                "& + .MuiSwitch-track": {
                                    backgroundColor: "#036666",
                                    opacity: 1,
                                    border: "none",
                                },
                                "&.Mui-disabled + .MuiSwitch-track": {
                                    opacity: 0.5,
                                },
                            },
                            "&.Mui-focusVisible .MuiSwitch-thumb": {
                                color: "#33cf4d",
                                border: "6px solid #FFFFFF",
                            },
                            "&.Mui-disabled .MuiSwitch-thumb": {
                                opacity: 0.5,
                            },
                            "&.Mui-disabled + .MuiSwitch-track": {
                                opacity: 0.7,
                            },
                            "& .MuiSwitch-input": {
                                border: "none",
                                background: "none",
                                display: "none"
                            }
                        },
                        thumb: {
                            width: "17px",
                            height: "17px",
                            color: "#036666"
                        },
                        track: {
                            borderRadius: "13px",
                            backgroundColor: "#EBF8F8",
                            opacity: 1,
                            transition: "background-color 500ms",
                            border: "1px solid #BFD4D4",
                            height: "auto"
                        },
                    },
                },
                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) {

        if (!prevProps.open && this.props.open) {
            this.setState({ TabValue: "staffDetails" });
        }
        
        if (this.props.staffId && prevProps.staffId !== this.props.staffId) {
            this.loadStaffData(this.props.staffId);
        }

        if (prevProps.multipleBooking !== this.props.multipleBooking) {
            this.setState({
                addFormData: {
                    ...this.state.addFormData,
                    staffMultipleBooking: String(this.props.multipleBooking || "false"),
                }
            });
        }
    }

    handleClose = () => {
        this.setState({
            addFormData: {
                fullName: "",
                profession: "",
                email: "",
                password: "",
                phoneNumber: "",
                note: "",
                image: "",
                serviceData: "",
                slotDuration: "",
                slotInterval: "",
                staffMultipleBooking: String(this.props.multipleBooking || "false"),
                scheduleData: "",
                specialDayData: "",
                holidayData: "",
            },
            staffRegistered: false,
        }, () => {
            this.props.onClose && this.props.onClose();
        });
    };


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

    handleServiceDataChange = (updatedServiceData) => {
        this.setState((prevState) => ({
            [this.props.staffId ? "editFormData" : "addFormData"]: {
                ...prevState[this.props.staffId ? "editFormData" : "addFormData"],
                serviceData: updatedServiceData,
            },
        }));
    }

    handleScheduleDataChange = (updatedScheduleData) => {
        this.setState((prevState) => ({
            [this.props.staffId ? "editFormData" : "addFormData"]: {
                ...prevState[this.props.staffId ? "editFormData" : "addFormData"],
                scheduleData: updatedScheduleData,
            },
        }));
    }

    handleSlotDurationChange = (value) => {
        this.setState((prevState) => ({
            [this.props.staffId ? "editFormData" : "addFormData"]: {
                ...prevState[this.props.staffId ? "editFormData" : "addFormData"],
                slotDuration: value,
            },
        }));
    }

    handleSlotIntervalChange = (value) => {
        this.setState((prevState) => ({
            [this.props.staffId ? "editFormData" : "addFormData"]: {
                ...prevState[this.props.staffId ? "editFormData" : "addFormData"],
                slotInterval: value,
            },
        }));
    }

    handleSpecialDayDataChange = (updatedSpecialDayData) => {
        this.setState((prevState) => ({
            [this.props.staffId ? "editFormData" : "addFormData"]: {
                ...prevState[this.props.staffId ? "editFormData" : "addFormData"],
                specialDayData: updatedSpecialDayData,
            },
        }));
    }

    handleHolidayDataChange = (updatedHolidayData) => {
        this.setState((prevState) => ({
            [this.props.staffId ? "editFormData" : "addFormData"]: {
                ...prevState[this.props.staffId ? "editFormData" : "addFormData"],
                holidayData: updatedHolidayData,
            },
        }));
    }

    handleInputChange = ( name, value ) => {
        const formState = this.props.staffId ? "editFormData" : "addFormData";
        this.setState(prevState => ({
            [formState]: { ...prevState[formState], [name]: value },
            errors: { ...prevState.errors, [name]: false }
        }));
    };

    handleInputChange = ( name, value ) => {
        const formState = this.props.staffId ? "editFormData" : "addFormData";
        this.setState(prevState => ({
            [formState]: { ...prevState[formState], [name]: value },
            errors: { ...prevState.errors, [name]: false }
        }));
    };

    handleStaffMultipleBooking = (event) => {
        const { name, checked } = event.target;
        const formState = this.props.staffId ? "editFormData" : "addFormData";
        this.setState(prevState => ({
            [formState]: { ...prevState[formState], [name]: String(checked) },
        }));
    }

    loadStaffData = (staffId) => {
        const staff = this.props.fetchStaffById(staffId);
        const { multipleBooking } = this.props;
        if (staff) {
            const staffMultipleBookingValue = staff.staff_multiple_booking 
                ? String(staff.staff_multiple_booking) 
                : String(multipleBooking || "false");
            
            this.setState({ 
                editFormData: {
                    fullName: staff.staff_name,
                    profession: staff.staff_profession,
                    email: staff.staff_email,
                    password: "",
                    phoneNumber: staff.staff_phone,
                    note: staff.staff_note,
                    image: staff.staff_img,
                    serviceData: staff.staff_services,
                    slotDuration: staff.staff_slot_duration,
                    slotInterval: staff.staff_slot_interval,
                    staffMultipleBooking: staffMultipleBookingValue,
                    scheduleData: staff.staff_shedule,
                    specialDayData: staff.staff_special_days,
                    holidayData: staff.staff_holidays,
                    googleConnection: staff.staff_google_connection,
                    outlookConnection: staff.staff_outlook_connection,
                    zoomUserId: staff.staff_zoom_id
                }
            });
        }
    };  

    handleStaffSubmit = ( isUpdate ) => {
        const { addFormData, editFormData, staffRegistered, staffRegisteredId } = this.state;
        const { staffId, fetchStaffData } = this.props;
        const ProStaffMultipleBooking = window.ProStaffMultipleBooking;
        const ZoomMeeting = window.ZoomMeeting;
        const dataToSend = {};
        const currentForm = staffId ? editFormData : addFormData;

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        const errors = {
            fullName: !currentForm.fullName,
            email: !currentForm.email,
            emailValidation: !emailRegex.test(currentForm.email),
            password: staffId ? false : !currentForm.password,
            phoneNumber: !currentForm.phoneNumber,
        };

        this.setState({ errors });
        
        if ( ( ! isUpdate ) && ( errors.fullName || errors.email || errors.emailValidation || errors.phoneNumber || (!staffId && errors.password) ) ) {
            return;
        }

        if (currentForm.serviceData) {
            Object.keys(currentForm.serviceData).forEach(serviceId => {
                const service = currentForm.serviceData[serviceId];
                if (service.price === null) {
                    service.price = service.servicePrice;
                }
                delete service.servicePrice;
            });
        }
        
        if (currentForm.scheduleData) {
            if (Object.values(currentForm.scheduleData).some(day => day.fromError || day.toError)) return;
        
            Object.keys(currentForm.scheduleData).forEach(dayKey => {
                const day = currentForm.scheduleData[dayKey];
                if (day.from && day.to) {
                    day.fromFormatted = dayjs( day.from ).format("hh:mm A");
                    day.toFormatted = dayjs( day.to ).format("hh:mm A");
                }
            });
        }

        if ( currentForm.specialDayData ) {
            if (Object.values(currentForm.specialDayData).some(index => index.dateError || index.fromError || index.toError)) return;

            Object.keys(currentForm.specialDayData).forEach(index => {
                const each = currentForm.specialDayData[index];
                if (each.date && each.from && each.to) {
                    each.dateFormated = dayjs( each.date ).format("YYYY-MM-DD");
                    each.fromFormatted = dayjs( each.from ).format("hh:mm A");
                    each.toFormatted = dayjs( each.to ).format("hh:mm A");
                }
            });
        }

        if ( currentForm.holidayData ) {
            if (Object.values(currentForm.holidayData).some(index => index.nameError || index.dateError)) return;

            Object.keys(currentForm.holidayData).forEach(index => {
                const each = currentForm.holidayData[index];
                if (each.date) {
                    each.dateFormated = dayjs( each.date ).format("YYYY-MM-DD");
                }
            });
        }

        this.setState({ loading: true });

        if ( staffId || staffRegisteredId ) {
            dataToSend.staff_id = staffId || staffRegisteredId;
        }
        dataToSend.staff_name = currentForm.fullName;
        dataToSend.staff_email = currentForm.email;
        dataToSend.staff_password = currentForm.password;
        dataToSend.staff_profession = currentForm.profession;
        dataToSend.staff_phone = currentForm.phoneNumber;
        dataToSend.staff_note = currentForm.note;
        dataToSend.staff_img = currentForm.image;
        dataToSend.selected_services = currentForm.serviceData ? JSON.stringify(currentForm.serviceData) : "";
        dataToSend.slot_duration = currentForm.slotDuration;
        dataToSend.slot_interval = currentForm.slotInterval;
        dataToSend.schedules = currentForm.scheduleData ? JSON.stringify(currentForm.scheduleData) : "";
        dataToSend.special_days = currentForm.specialDayData ? JSON.stringify(currentForm.specialDayData) : "";
        dataToSend.holidays = currentForm.holidayData ? JSON.stringify(currentForm.holidayData) : "";

        if ( ProStaffMultipleBooking ) {
            dataToSend.staff_multiple_booking = currentForm.staffMultipleBooking;
        }

        if ( ZoomMeeting ) {
            dataToSend.staff_zoom_id = currentForm.zoomUserId;
        }

        console.log( dataToSend );

        const endpoint = staffId ? `${wpbAdmin.root}bookify/v1/update-staff` : staffRegistered ? `${wpbAdmin.root}bookify/v1/update-staff`: `${wpbAdmin.root}bookify/v1/add-staff`;
        fetch(endpoint, { 
            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 ) {
                
                if ( response.redirect ) {
                    window.location.href = response.redirect;
                }

                this.setState({ 
                    snackbarOpen: true,
                    snackbarMessage: response.message,
                    snackbarType: "success",
                    errors: { fullName: false, email: false, password: false, phoneNumber: false },
                    staffRegistered: true,
                    staffRegisteredId: response.success,
                    loading: false
                });
                fetchStaffData();
            } 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, staffId, services, slotDuration, slotInterval, dateFormat, timeFormat, currency, toggleGcal, toggleOcal, zoomUsers } = this.props;
        const { theme, addFormData, editFormData, errors, TabValue, staffRegistered, staffRegisteredId, snackbarOpen, snackbarMessage, snackbarType, loading } = this.state;
        const currentForm = staffId ? editFormData : addFormData;
        const staffSlotDuration = currentForm.slotDuration ? currentForm.slotDuration : slotDuration;
        const staffSlotInterval = currentForm.slotInterval ? currentForm.slotInterval : slotInterval;

        return (
            <>
                <ThemeProvider theme={theme}>
                    <Dialog onClose={this.handleClose} open={open} fullWidth sx={{"& .MuiDialog-paper":{maxWidth:"42rem"}, height:"80%", padding:"4% 0%"}}>
                        <DialogTitle sx={{ display: "flex", alignItems: "center" }}>
                            {staffId ? __("Edit Staff", "bookify") : __("Add Staff", "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="staffDetails" label={__("Staff Details", "bookify")} />
                                    <Tab value="Services" label={__("Services", "bookify")} disabled={staffId ? false : !staffRegistered}/>
                                    <Tab value="Schedule" label={__("Schedule", "bookify")} disabled={staffId ? false : !staffRegistered}/>
                                    <Tab value="specialDays" label={__("Special Days", "bookify")} disabled={staffId ? false : !staffRegistered}/>
                                    <Tab value="Holidays" label={__("Holidays", "bookify")} disabled={staffId ? false : !staffRegistered}/>
                                </TabList>
                                
                                <TabPanel value="staffDetails" index={0} >
                                    <StaffDetailsForm 
                                        formData={currentForm}
                                        errors={errors}
                                        staffId={staffId}
                                        staffRegistered={staffRegistered}
                                        staffRegisteredId={staffRegisteredId}
                                        onChange={this.handleInputChange}
                                        toggleGcal={toggleGcal}
                                        toggleOcal={toggleOcal}
                                        zoomUsers={zoomUsers}
                                        theme={theme}
                                    />
                                </TabPanel>
                                <TabPanel value="Services" index={1}>
                                    <ServiceDetailsForm 
                                        formData={currentForm.serviceData} 
                                        services={services}
                                        currency={currency}
                                        handleServiceData={this.handleServiceDataChange}
                                        theme={theme}
                                    />
                                </TabPanel>
                                <TabPanel value="Schedule" index={2}>
                                    <ScheduleDetailsForm
                                        scheduleData={currentForm.scheduleData}
                                        staffMultipleBooking={currentForm.staffMultipleBooking}
                                        timeFormat={timeFormat}
                                        slotDuration={staffSlotDuration}
                                        slotInterval={staffSlotInterval}
                                        handleScheduleData={this.handleScheduleDataChange}
                                        handleSlotDuration={this.handleSlotDurationChange}
                                        handleSlotInterval={this.handleSlotIntervalChange}
                                        handleStaffMultipleBooking={this.handleStaffMultipleBooking}
                                        theme={theme}
                                    />
                                </TabPanel>
                                <TabPanel value="specialDays" index={3}>
                                    <SpecialDayDetailsForm
                                        formData={currentForm.specialDayData}
                                        dateFormat={dateFormat}
                                        timeFormat={timeFormat}
                                        handleSpecialDayData={this.handleSpecialDayDataChange}
                                        theme={theme}
                                    />
                                </TabPanel>
                                <TabPanel value="Holidays" index={4}>
                                    <HolidayDetailsForm
                                        formData={currentForm.holidayData}
                                        dateFormat={dateFormat}
                                        timeFormat={timeFormat}
                                        handleHolidayData={this.handleHolidayDataChange}
                                        theme={theme}
                                    />
                                </TabPanel>
                            </TabContext>
                        </DialogContent>
                        
                        <Divider sx={{borderColor:"#DDEEEE"}} />

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

export default AddStaff;