import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import {
    Stack, Typography, Box, FormControl, 
    TextField, InputAdornment, Button, Grid
} from "@mui/material";
import SearchIcon from "@mui/icons-material/Search";
import AddIcon from "@mui/icons-material/Add";
import AddService from "./AddService";
import CategorySection from "./CategorySection";
import ServiceTable from "./ServiceTable";
import { 
    downloadCSV, openDialog, closeDialog
} 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 Services extends Component {
    state = {
        headCells: [
            { id: "service_id", label: "ID", priority: 0 },
            { id: "service_name", label: "Service Name", priority: 5 },
            { id: "category_name", label: "Service Category", priority: 10 },
            { id: "service_price", label: "Price", priority: 15 },
            { id: "action", label: "Action", priority: 20 },
        ],
        allServiceData: [],
        TableData: [],
        searchText: "",
        CategoryData: [],
        totalCount: 0,
        page: 0,
        pageSize: 10,
        orderBy: "id",
        order: "desc",
        serviceID: null,
        editDialogHandle: null,
        currency: "USD",
        generalGmeet: false,
        gmeetDisable: true,
        zoomDisable: true,
        ServiceDataLoading: true,
        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() {
        this.fetchServiceData();

        const title = window.wp.hooks.applyFilters("bookify_service_title", "Services");
        this.setState({ title });
    }

    fetchServiceData = (page = 1, pageSized = 10, changePageSize = false, category = "") => {
        const { searchText, pageSize } = this.state;
        let perPageSized = pageSize;
        if ( changePageSize ) {
            perPageSized = pageSized;
        }
        const categoryQuery = category.length > 0 ? `&categories=${category.join(",")}` : "";
        const searchQuery = searchText ? `&search=${encodeURIComponent(searchText)}` : "";
        this.setState({ ServiceDataLoading: true });


        fetch(`${wpbAdmin.root}bookify/v1/services?page=${page}&pageSize=${perPageSized}${categoryQuery}${searchQuery}`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpApiSettings.nonce
            }
        })
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                allServiceData: data.serviceData,
                TableData: data.serviceData,
                totalCount: data.total,
                currency: data.currency,
                generalGmeet: data.general_gmeet,
                gmeetDisable: data.gmeet_disable,
                zoomDisable: data.zoom_disable
            });
        })
        .catch((error) => {
            console.error("Error fetching data:", error);
        })
        .finally(() => {
            this.setState({ ServiceDataLoading: false });
        });
    };

    fetchServiceById = (serviceId) => {
        return this.state.TableData.find(service => service.service_id === serviceId);
    };

    handleSearchData = (event) => {
        const searchText = event.target.value.toLowerCase();
        const { allServiceData } = this.state;
    
        let filteredData;
    
        if (searchText == "") {
            filteredData = allServiceData;
        } else {
            filteredData = allServiceData.filter(service => {
                return (
                    service.service_name.toLowerCase().includes(searchText) ||
                    service.category_name.toLowerCase().includes(searchText) ||
                    service.service_price.toLowerCase().includes(searchText)
                );
            });
        }
        
        this.setState({ 
            searchText: event.target.value, 
            TableData: filteredData 
        });
    };

    handleProVerion = () => {
        window.open("https://wpbookify.com/pricing/", "_blank");
    }

    render() {
        
        const { headCells, TableData, CategoryData, currency, theme, title, totalCount, pageSize, page, orderBy, order, editDialogHandle, ServiceDataLoading, generalGmeet, gmeetDisable, zoomDisable } = this.state;

        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 services"
                                    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>
                        <Box Component="div" sx={{display:"flex", justifyContent:"flex-start", gap:"20px"}}>
                            <Box Component="div">
                                <Button variant="wpbkThemeCSVBtn" startIcon={<CsvIcon />} onClick={() => downloadCSV(this.state, "Bookify Services")} >
                                    {__("Export to CSV", "bookify")}
                                </Button>
                            </Box>
                            <Box Component="div">
                                <Button variant="wpbkThemeBtn" startIcon={<AddIcon />} onClick={() => openDialog(this.state, this.setState.bind(this), "AddServiceDialog")} >
                                    {__("Add Service", "bookify")}
                                </Button>
                                <AddService
                                    open={this.state.AddServiceDialog}
                                    onClose={() => closeDialog(this.state, this.setState.bind(this), "AddServiceDialog")}
                                    AllCategories={CategoryData}
                                    fetchServiceById={this.fetchServiceById}
                                    fetchServiceData={this.fetchServiceData}
                                    serviceId={editDialogHandle}
                                    currency={currency}
                                    generalGmeet={generalGmeet}
                                    gmeetDisable={gmeetDisable}
                                    zoomDisable={zoomDisable}
                                />
                            </Box>
                        </Box>
                    </Box>
                </Box>
                <Grid container>
                    <Grid item container md={3} direction="column">
                        <CategorySection
                            CategoryData={CategoryData}
                            fetchServiceData={this.fetchServiceData}
                            state={this.state}
                            setState={this.setState.bind(this)}
                        />
                    </Grid>

                    <Grid item md={9}>
                        <Box component="section">
                            <Box component="div" sx={{m:"2em"}}>
                                <ServiceTable
                                    state={this.state}
                                    setState={this.setState.bind(this)}
                                    headCells={headCells}
                                    fetchServiceData={this.fetchServiceData}
                                    TableData={TableData}
                                    totalCount={totalCount}
                                    pageSize={pageSize}
                                    page={page}
                                    orderBy={orderBy}
                                    order={order}
                                    currency={currency}
                                    ServiceDataLoading={ServiceDataLoading}
                                />
                            </Box>
                        </Box>
                    </Grid>
                </Grid>
            </ThemeProvider>
        );
    }
}

export default Services;