import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import {
    Stack, Typography, Box, FormControl,
    TextField, InputAdornment, Button,
} from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import SearchIcon from "@mui/icons-material/Search";
import AddStaff from "./AddStaff";
import StaffTable from "./StaffTable";
import { 
    downloadCSV, openDialog, closeDialog
} from "../../functions";
import { GetProModal } from "../../functions";
import BookifyLogo from "../../assets/bookify-logo.png";
import { ReactComponent as CrownIcon } from "../../assets/crown.svg";
import { ReactComponent as CsvIcon } from "../../assets/csv.svg";

class Staffs extends Component {
    state = {
        headCells: [
            { id: "id", label: "ID", priority: 0 },
            { id: "staff_name", label: "Staff Name", priority: 5 },
            { id: "staff_phone", label: "Phone", priority: 10 },
            { id: "staff_email", label: "Email", priority: 15 },
            { id: "service_assigned", label: "Services", priority: 20 },
            { id: "action", label: "Action", priority: 25 },
        ],
        services: [],
        allStaffData: [],
        TableData: [],
        searchText: "",
        dateFormat: "",
        timeFormat: "",
        slotDuration: "30",
        slotInterval: "15",
        multipleBooking: false,
        totalCount: 0,
        page: 0,
        pageSize: 10,
        order: "desc",
        orderBy: "id",
        currency: "USD",
        editDialogHandle: null,
        isStaff: false,
        dataLoading: true,
        toggleGoogleCalendar: false,
        toggleOutlookCalendar: false,
        zoomUsers: [],
        proModalOpen: 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%",
                                "&:hover": {
                                    backgroundColor: "#025151",
                                    color: "#FFFFFF"
                                },
                                "&.Mui-disabled": {
                                    color: "#FFFFFF",
                                    opacity: 0.7,
                                }
                            },
                        },
                        {
                            props: { variant: "wpbkThemeCSVBtn" },
                            style: {
                                border: "1px solid #BFD4D4",
                                color: "#042626",
                                textTransform: "capitalize",
                                height: "100%",
                                width: "12em",
                                "&.Mui-disabled": {
                                    color: "#FFFFFF",
                                    opacity: 0.7,
                                }
                            },
                        },
                    ],
                },
                MuiStack: {
                    styleOverrides: {
                        root: {
                            backgroundColor: "#FFFFFF",
                            border: "1px solid #DDEEEE",
                            borderRadius: "4px",
                        },
                    },
                },
            },
        }),
    };

    componentDidMount() {
        const title = window.wp.hooks.applyFilters("bookify_staff_title", "Staffs");
        this.setState({ title });

        this.fetchStaffData();
    }
    
    fetchStaffData = (page = 1, pageSized = 10, changePageSize = false) => {
        const { searchText, pageSize } = this.state;
        let perPageSized = pageSize;
        if ( changePageSize ) {
            perPageSized = pageSized;
        }
        const searchQuery = searchText ? `&search=${encodeURIComponent(searchText)}` : "";
        this.setState({ dataLoading: true });

        fetch(`${wpbAdmin.root}bookify/v1/staffs?page=${page}&pageSize=${perPageSized}${searchQuery}`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpApiSettings.nonce
            }
        })
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                allStaffData: data.data,
                TableData: data.data,
                totalCount: data.total,
                dateFormat: data.dateFormat,
                timeFormat: data.timeFormat,
                services: data.services,
                slotDuration: data.duration,
                slotInterval: data.interval,
                currency: data.currency,
                isStaff: data.is_staff,
                multipleBooking: data.multipleBooking,
                toggleGoogleCalendar: data.toggleGcal,
                toggleOutlookCalendar: data.toggleOcal,
                zoomUsers: data.zoomUsers,
            });
        })
        .catch((error) => {
            console.error("Error fetching data:", error);
        })
        .finally(() => {
            this.setState({ dataLoading: false });
        });
    };

    fetchStaffById = (staffId) => {
        return this.state.TableData.find(staff => staff.id === staffId);
    };

    handleSearchData = (event) => {
        const searchText = event.target.value.toLowerCase();
        const { allStaffData } = this.state;
    
        let filteredData;
    
        if (searchText == "") {
            filteredData = allStaffData;
        } else {
            filteredData = allStaffData.filter(staff => {
                return (
                    staff.staff_name.toLowerCase().includes(searchText) ||
                    staff.staff_phone.toLowerCase().includes(searchText) ||
                    staff.staff_email.toLowerCase().includes(searchText) ||
                    staff.service_assigned.toLowerCase().includes(searchText)
                );
            });
        }
        
        this.setState({ 
            searchText: event.target.value, 
            TableData: filteredData 
        });
    };

    handleProVerion = () => {
        window.open("https://wpbookify.com/pricing/", "_blank");
    }

    handleProPopup = () => {
        this.setState({
            proModalOpen: true
        });
        return;
    }

    render() {
        const { headCells, TableData, services, theme, title, orderBy, order, totalCount, pageSize, page, editDialogHandle, slotDuration, slotInterval, dateFormat, timeFormat, currency, isStaff, multipleBooking, dataLoading, toggleGoogleCalendar, toggleOutlookCalendar, zoomUsers, proModalOpen } = this.state;
        const staffLength = TableData.length;
        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">
                            <FormControl sx={{width:"40em"}}>
                                <TextField
                                    variant="outlined"
                                    placeholder="Search staffs"
                                    sx={{
                                        height: "45px",
                                        border: "1px solid #BFD4D4",
                                        borderRadius: "4px",
                                        color: "#789595",
                                        justifyContent: "center",
                                        "& fieldset": {
                                            border: "none",
                                        }
                                    }}
                                    onChange={this.handleSearchData}
                                    InputProps={{
                                        sx: {
                                            paddingRight: "5px",
                                            "& input": {
                                                padding: "11px",
                                                "::placeholder": {
                                                    color: "#789595",
                                                    opacity: 1
                                                },
                                            },
                                        },
                                        endAdornment: (
                                            <InputAdornment position="start" sx={{color: "#042626"}}>
                                                <SearchIcon />
                                            </InputAdornment>
                                        ),
                                    }}
                                />
                            </FormControl>
                        </Box>
                        { ! isStaff && (
                            <Box Component="div" sx={{display:"flex", justifyContent:"flex-start", gap:"20px"}}>
                                <Box Component="div">
                                    <Button variant="wpbkThemeCSVBtn" startIcon={<CsvIcon />} onClick={() => downloadCSV(this.state, "Bookify Staffs")} >
                                        {__("Export to CSV", "bookify")}
                                    </Button>
                                </Box>
                                <Box Component="div" sx={{cursor:ProLocation ? "default" : staffLength >= 1 && "not-allowed"}}>
                                    <Button variant="wpbkThemeBtn" startIcon={<AddIcon />} onClick={() => ProLocation ? openDialog(this.state, this.setState.bind(this), "AddStaffDialog") : staffLength >= 1 ? this.handleProPopup() : openDialog(this.state, this.setState.bind(this), "AddStaffDialog")} >
                                        {__("Add Staff", "bookify")}
                                    </Button>
                                </Box>
                            </Box>
                        )}
                        <AddStaff
                            open={this.state.AddStaffDialog}
                            onClose={() => closeDialog(this.state, this.setState.bind(this), "AddStaffDialog")}
                            fetchStaffById={this.fetchStaffById}
                            fetchStaffData={this.fetchStaffData}
                            dateFormat={dateFormat}
                            timeFormat={timeFormat}
                            services={services}
                            staffId={editDialogHandle}
                            slotDuration={slotDuration}
                            slotInterval={slotInterval}
                            currency={currency}
                            multipleBooking={multipleBooking}
                            toggleGcal={toggleGoogleCalendar}
                            toggleOcal={toggleOutlookCalendar}
                            zoomUsers={zoomUsers}
                        />
                    </Box>
                    <Box component="div" sx={{m:"2em"}}>
                        <StaffTable
                            state={this.state}
                            setState={this.setState.bind(this)}
                            headCells={headCells}
                            fetchStaffData={this.fetchStaffData}
                            TableData={TableData}
                            totalCount={totalCount}
                            pageSize={pageSize}
                            page={page}
                            orderBy={orderBy}
                            order={order}
                            isStaff={isStaff}
                            dataLoading={dataLoading}
                        />
                    </Box>
                </Box>
                <GetProModal 
                    open={proModalOpen}
                    onClose={() => this.setState({ proModalOpen: false })}
                />
            </ThemeProvider>
        );
    }
}

export default Staffs;
