import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { 
    Stack, Typography, Box, Button,
    FormControl, Select, MenuItem
} from "@mui/material";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin from "@fullcalendar/interaction";
import AddIcon from "@mui/icons-material/Add";
import AddAppointment from "./AddAppointment";
import { 
    openDialog, closeDialog
} from "../../functions";
import dayjs from "dayjs";
import BookifyLogo from "../../assets/bookify-logo.png";
import { ReactComponent as CrownIcon } from "../../assets/crown.svg";

class Calendar extends Component {
    state = {
        CalenderData: [],
        dateFormat: "",
        timeFormat: "12-hour",
        priorToggle: "Disable",
        priorTime: "3",
        staffs: [],
        locations: [],
        services: [],
        customers: [],
        calendarStaffFilter: "none",
        defaultAppointmentStatus: "Pending",
        isStaff: false,
        theme: createTheme({
            typography: {
                h2: {
                    fontSize: "2em",
                    textTransform: "capitalize",
                    color: "#587373",
                    marginLeft: "10px"
                },
            },
            components: {
                MuiButton: {
                    variants: [
                        {
                            props: { variant: "wpbkGetPro" },
                            style: {
                                textTransform: "capitalize",
                                backgroundColor: "#FFDD9A",
                                boxShadow: "none",
                                color: "#735928",
                                padding: "10px 20px",
                                fontWeight: 600,
                                "&:hover": {
                                    backgroundColor: "#f5cd7d",
                                    boxShadow: "none",
                                },
                            },
                        },
                        {
                            props: { variant: "wpbkThemeBtn" },
                            style: {
                                borderColor: "none",
                                backgroundColor: "#036666",
                                color: "#FFFFFF",
                                textTransform: "capitalize",
                                width: "13em",
                                height: "100%",
                                maxHeight: "47px",
                                "&:hover": {
                                    backgroundColor: "#025151",
                                    color: "#FFFFFF"
                                },
                                "&.Mui-disabled": {
                                    color: "#FFFFFF",
                                    opacity: 0.7,
                                }
                            },
                        },
                    ],
                },
                MuiStack: {
                    styleOverrides: {
                        root: {
                            backgroundColor: "#FFFFFF",
                            border: "1px solid #DDEEEE",
                            borderRadius: "4px",
                        },
                    },
                },
                MuiMenuItem: {
                    styleOverrides: {
                        root: {
                            marginLeft: "3px",
                            marginRight: "3px",
                            paddingLeft: "10px",
                            paddingRight: "10px",
                            borderRadius: "8px"
                        },
                    },
                }
            },
        }),
    };

    componentDidMount() {
        const title = window.wp.hooks.applyFilters("bookify_calendar_title", "Calendar");
        this.setState({ title });

        this.fetchCalendarData();
    }

    fetchCalendarData = (searchStaff = "") => {
        let queryString = "";
        if ( searchStaff ) {
            queryString = `?staff=${searchStaff}`
        }

        fetch(`${wpbAdmin.root}bookify/v1/calendar${queryString}`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpApiSettings.nonce
            }
        })
        .then(response => response.json())
        .then(data => {
            this.setState({
                CalenderData: data.calender_data,
                dateFormat: data.dateFormat,
                timeFormat: data.timeFormat,
                priorToggle: data.priorToggle,
                priorTime: data.priorTime,
                staffs: data.staffs,
                locations: data.locations,
                services: data.services,
                customers: data.customers,
                defaultAppointmentStatus: data.defaultAppointmentStatus,
                isStaff: data.is_staff
            });
        })
        .catch((error) => {
            console.error("Error fetching data:", error);
        })
    };

    CalendarEvents = () => {
        const { timeFormat } = this.state;
        const timeFormated = timeFormat == "12-hour" ? "hh:mm A" : "HH:mm";

        let events = this.state.CalenderData.map(item => {
            let Color;
            let textColor;
            let slot = JSON.parse( item.appointment_duration ).map((time) => {
                            const [start, end] = time.split(" - ");
                            return `${dayjs(`1970-01-01 ${start}`).format(timeFormated)} - ${dayjs(`1970-01-01 ${end}`).format(timeFormated)}`;
                        }).join(" | ");


            switch ( item.appointment_status ) {
                case "Pending":
                    Color = "#FFF4E3";
                    textColor = "#74561C";
                    break;
                case "Confirmed":
                    Color = "#E7F3D7";
                    textColor = "#545E48";
                    break;
                case "Delayed":
                    Color = "#F3E4FF";
                    textColor = "#54485E";
                    break;
                case "Completed":
                    Color = "#E3EEFF";
                    textColor = "#1C3E74";
                    break;
                case "On Hold":
                    Color = "#F0F0F0";
                    textColor = "#555555";
                    break;
                case "Cancelled":
                    Color = "#FFE9E3";
                    textColor = "#74311C";
                    break;
                default:
                    Color = "#9E9E9E";
                    textColor = "#FFFFFF";
            }
    
            return {
                title: `${item.customer_name} | ${slot}`,
                date: item.appointment_date,
                color: Color,
                textColor: textColor
            };
        });
        return events;
    };

    handleMaxDates = ( nowDate ) => {
        const { priorToggle, priorTime } = this.state;

        let maxDate = null;
        if ( priorToggle == "Enable" ) {
            maxDate = dayjs(nowDate).add(parseInt(priorTime), "month").format( "YYYY-MM-DD" );
        }

        return { end: maxDate };
    }

    handleStaffChange = ( event ) => {
        const { value } = event.target;
        this.setState({
            calendarStaffFilter: value,
        });

        this.fetchCalendarData( value );
    }

    handleProVerion = () => {
        window.open("https://wpbookify.com/pricing/", "_blank");
    }

    render() {

        const { dateFormat, theme, title, staffs, locations, services, customers, calendarStaffFilter, priorToggle, priorTime, defaultAppointmentStatus, isStaff } = this.state;
        const events = this.CalendarEvents();

        const ProLocation = window.ProLocation;

        return (
            <ThemeProvider theme={theme}>
                <Stack spacing={2} mb={"2em"} p={"1.5em 2em"} direction={"row"} alignItems={"center"} justifyContent={"space-between"}>
                    <Box sx={{display:"flex", direction:"row", alignItems:"flex-end"}}>
                        <img src={BookifyLogo} alt="Bookify Logo" style={{height:40}} />
                        <Typography variant={"h2"}>{title}</Typography>
                    </Box>
                    { ! ProLocation && 
                        <Box>
                            <Button variant="wpbkGetPro" startIcon={<CrownIcon />} onClick={this.handleProVerion}>
                                {__("Get Pro Version", "bookify")}
                            </Button>
                        </Box>
                    }
                </Stack>
                <Box component={"section"}>
                    <Box Component={"div"} sx={{display:"flex", justifyContent:"space-between", m:"2em", p:"15px", backgroundColor:"#FFFFFF", border:"1px solid #DDEEEE", borderRadius:"4px"}}>
                        <Box component={"div"} sx={{display:"flex", justifyContent:"flex-end", gap:"20px"}}>
                            <Box component={"span"} sx={{display:"flex", alignItems:"center"}}>
                                <Box sx={{width:15, height:15, borderRadius:"2px", backgroundColor:"#FFC46A", mr:"5px"}}/>
                                <Typography variant={"subtitle1"}>{__("Pending", "bookify")}</Typography>
                            </Box>
                            <Box component={"span"} sx={{display:"flex", alignItems:"center"}}>
                                <Box sx={{width:15, height:15, borderRadius:"2px", backgroundColor:"#A5CF6E", mr:"5px"}}/>
                                <Typography variant={"subtitle1"}>{__("Confirmed", "bookify")}</Typography>
                            </Box>
                            <Box component={"span"} sx={{display:"flex", alignItems:"center"}}>
                                <Box sx={{width:15, height:15, borderRadius:"2px", backgroundColor:"#CF94FF", mr:"5px"}}/>
                                <Typography variant={"subtitle1"}>{__("Delayed", "bookify")}</Typography>
                            </Box>
                            <Box component={"span"} sx={{display:"flex", alignItems:"center"}}>
                                <Box sx={{width:15, height:15, borderRadius:"2px", backgroundColor:"#81B2FF", mr:"5px"}}/>
                                <Typography variant={"subtitle1"}>{__("Completed", "bookify")}</Typography>
                            </Box>
                            <Box component={"span"} sx={{display:"flex", alignItems:"center"}}>
                                <Box sx={{width:15, height:15, borderRadius:"2px", backgroundColor:"#C8C8C8", mr:"5px"}}/>
                                <Typography variant={"subtitle1"}>{__("On Hold", "bookify")}</Typography>
                            </Box>
                            <Box component={"span"} sx={{display:"flex", alignItems:"center"}}>
                                <Box sx={{width:15, height:15, borderRadius:"2px", backgroundColor:"#FF9182", mr:"5px"}}/>
                                <Typography variant={"subtitle1"}>{__("Cancelled", "bookify")}</Typography>
                            </Box>
                        </Box>
                        { ! isStaff && (
                            <Box Component={"div"} sx={{display:"flex", gap:"20px"}}>
                                <FormControl sx={{width:"168px", backgroundColor:"#FFFFFF"}}>
                                    <Select
                                        name={"calendarStaffFilter"}
                                        value={calendarStaffFilter}
                                        onChange={this.handleStaffChange}
                                        variant={"outlined"}
                                        sx={{
                                            border: "1px solid #BFD4D4",
                                            height: "47px",
                                            "& fieldset": {
                                                border: "none",
                                            },
                                        }}
                                    >
                                        <MenuItem key={"none"} value={"none"}>
                                            {__("All Staffs", "bookify")}
                                        </MenuItem>
                                        {staffs.map((value) => (
                                            <MenuItem key={value.id} value={value.id}>
                                                {value.staff_name}
                                            </MenuItem>
                                        ))}
                                    </Select>
                                </FormControl>
                                <Button variant={"wpbkThemeBtn"} startIcon={<AddIcon />} onClick={() => openDialog(this.state, this.setState.bind(this), "AddAppointmentDialog")}>
                                    {__("Add Appointment", "bookify")}
                                </Button>
                                <AddAppointment
                                    open={this.state.AddAppointmentDialog}
                                    onClose={() => closeDialog(this.state, this.setState.bind(this), "AddAppointmentDialog")}
                                    fetchCalendarData={this.fetchCalendarData}
                                    dateFormat={dateFormat}
                                    priorToggle={priorToggle}
                                    priorTime={priorTime}
                                    locations={locations}
                                    services={services}
                                    customers={customers}
                                    defaultStatus={defaultAppointmentStatus}
                                />
                            </Box>
                        )}
                    </Box>
                    <Box component={"section"} sx={{m:"2em", p:"15px", backgroundColor:"#FFFFFF", border:"1px solid #DDEEEE", borderRadius:"4px"}}>
                        <FullCalendar
                            plugins={[dayGridPlugin, interactionPlugin]}
                            initialView="dayGridMonth"
                            validRange={(nowDate) => this.handleMaxDates(nowDate)}
                            events={events}
                            headerToolbar={{
                                left: "dayGridMonth,dayGridWeek,dayGridDay",
                                center: "prev,title,next",
                                right: "today",
                            }}
                             buttonHints={{
                                dayGridMonth: __("Month View", "bookify"),
                                dayGridWeek: __("Week View", "bookify"),
                                dayGridDay: __("Day View", "bookify"),
                            }}
                            buttonText={{
                                today: __("Today", "bookify"),
                                month: __("Month", "bookify"),
                                week: __("Week", "bookify"),
                                day: __("Day", "bookify"),
                            }}
                            eventDidMount={(info) => {
                                info.el.setAttribute("title", info.event.title);
                            }}
                        />
                    </Box>
                </Box>
            </ThemeProvider>
        );
    }
}

export default Calendar;
