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 AddNotification from "./AddNotification";
import NotificationTable from "./NotificationTable";
import { 
    openDialog, closeDialog
} from "../../functions";
import BookifyLogo from "../../assets/bookify-logo.png";
import { ReactComponent as CrownIcon } from "../../assets/crown.svg";

class Notification extends Component {
    state = {
        allNotificationData: [],
        TableData: [],
        searchText: "",
        totalCount: 0,
        page: 0,
        pageSize: 10,
        order: "desc",
        orderBy: "id",
        dataLoading: false,
        editDialogHandle: null,
        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,
                                }
                            },
                        },
                    ],
                },
                MuiStack: {
                    styleOverrides: {
                        root: {
                            backgroundColor: "#FFFFFF",
                            border: "1px solid #DDEEEE",
                            borderRadius: "4px",
                        },
                    },
                },
            },
        }),
    };

    componentDidMount() {
        this.fetchNotificationData();
        
        const title = window.wp.hooks.applyFilters("bookify_notification_title", "Notifications");
        this.setState({ title });
    }

    fetchNotificationById = (notificationId) => {
        return this.state.TableData.find(notification => notification.id === notificationId);
    };

    fetchNotificationData = (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/notification?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({
                allNotificationData: data.notificationData,
                TableData: data.notificationData,
                totalCount: data.total,
            });
        })
        .catch((error) => {
            console.error("Error fetching data:", error);
        })
        .finally(() => {
            this.setState({ dataLoading: false });
        });
    };

    handleSearchData = (event) => {
        const searchText = event.target.value.toLowerCase();
        const { allNotificationData } = this.state;
    
        let filteredData;
    
        if (searchText == "") {
            filteredData = allNotificationData;
        } else {
            filteredData = allNotificationData.filter(notification => {
                return (
                    notification.notification_name.toLowerCase().includes(searchText) ||
                    notification.notification_event.toLowerCase().includes(searchText)
                );
            });
        }
        
        this.setState({ 
            searchText: event.target.value, 
            TableData: filteredData 
        });
    };

    handleProVerion = () => {
        window.open("https://wpbookify.com/pricing/", "_blank");
    }

    render() {
        const { TableData, theme, title, orderBy, order, totalCount, pageSize, page, editDialogHandle, dataLoading } = 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 notifications"
                                    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">
                            <Button variant="wpbkThemeBtn" startIcon={<AddIcon />} onClick={() => openDialog(this.state, this.setState.bind(this), "AddNotificationDialog")} >
                                {__("Add Notification", "bookify")}
                            </Button>
                            <AddNotification
                                open={this.state.AddNotificationDialog}
                                onClose={() => closeDialog(this.state, this.setState.bind(this), "AddNotificationDialog")}
                                fetchNotificationById={this.fetchNotificationById}
                                fetchNotificationData={this.fetchNotificationData}
                                notificationId={editDialogHandle}
                            />
                        </Box>
                    </Box>
                    <Box component="div" sx={{m:"2em"}}>
                        <NotificationTable
                            state={this.state}
                            setState={this.setState.bind(this)}
                            fetchNotificationData={this.fetchNotificationData}
                            TableData={TableData}
                            totalCount={totalCount}
                            pageSize={pageSize}
                            page={page}
                            orderBy={orderBy}
                            order={order}
                            dataLoading={dataLoading}
                        />
                    </Box>
                </Box>
            </ThemeProvider>
        );
    }
}

export default Notification;
