import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import {
    Box, Grid, Typography, Stack, Button,
    Checkbox, IconButton, Chip, Skeleton
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import AddIcon from "@mui/icons-material/Add";
import ModeIcon from "@mui/icons-material/Mode";
import DeleteIcon from "@mui/icons-material/Delete";
import AddCategory from "./AddCategory";
import { openDialog, closeDialog } from "../../functions";
import { SnackbarNotice, ConfirmationDialog } from "../../functions";
import { ReactComponent as NoCategory } from "../../assets/no-category.svg";

class CategorySection extends Component {
    state = {
        selectedCategories: [],
        AddCategoryDialog: false,
        editDialogHandle: null,
        snackbarOpen: false,
        snackbarMessage: "",
        snackbarType: "success",
        confirmationDialogOpen: false,
        confirmationLoading: false,
        categoryIdToDelete: null,
        CategoryDataLoading: true,
        theme: createTheme({
            components: {
                MuiButton: {
                    variants: [
                        {
                            props: { variant: "wpbkThemeBtn" },
                            style: {
                                borderColor: "none",
                                backgroundColor: "#036666",
                                color: "#FFFFFF",
                                textTransform: "capitalize",
                                padding: "16px 0px",
                                width: "13em",
                                height: "45px",
                                "&:hover": {
                                    backgroundColor: "#025151",
                                    color: "#FFFFFF"
                                },
                                "&.Mui-disabled": {
                                    color: "#FFFFFF",
                                    opacity: 0.7,
                                }
                            },
                        }
                    ],
                },
                MuiChip: {
                    variants: [
                        {
                            props: { variant: "wpbkChip" },
                            style: {
                                color: "#036666",
                                backgroundColor: "#F4FDFD",
                                border: "1px solid #30AAA7",
                            },
                        },
                    ],
                    styleOverrides: {
                        deleteIcon: {
                            color: "#036666",
                            fontSize: "16px",
                            "&:hover": {
                                color: "#30AAA7",
                            },
                        },
                    },
                },
                MuiStack: {
                    styleOverrides: {
                        root: {
                            backgroundColor: "#FFFFFF",
                            border: "1px solid #DDEEEE",
                            borderRadius: "4px",
                        },
                    },
                },
            },
        }),
    };

    componentDidMount() {
        this.fetchCategoryData();
    }

    handleCategorySelect = (categoryId) => {
        const { selectedCategories } = this.state;
        const { pageSize } = this.props.state;
        const index = selectedCategories.indexOf(categoryId);
        let newSelectedCategories = [...selectedCategories];

        if (index === -1) {
            newSelectedCategories.push(categoryId);
        } else {
            newSelectedCategories.splice(index, 1);
        }

        this.setState({ selectedCategories: newSelectedCategories });
        this.props.fetchServiceData(1, pageSize, true, newSelectedCategories);
    };

    fetchCategoryById = (categoryId) => {
        return this.props.CategoryData.find(category => category.id === categoryId);
    };

    fetchCategoryData = () => {
        this.setState({ CategoryDataLoading: true });

        fetch(`${wpbAdmin.root}bookify/v1/categories`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpApiSettings.nonce
            }
        })
        .then(response => response.json())
        .then(data => {
            this.props.setState(prevState => ({
                ...prevState,
                CategoryData: data.categoryData,
            }));
        })
        .catch(error => {
            console.error("Error fetching data:", error);
        })
        .finally(() => {
            this.setState({ CategoryDataLoading: false });
        });
    };

    handleDeleteCategory = (categoryId) => {
        this.setState({ confirmationDialogOpen: true, categoryIdToDelete: categoryId });
    };

    confirmCategoryDelete = () => {
        const { categoryIdToDelete } = this.state;
        this.setState({ confirmationLoading: true });

        const dataToSend = {};
        dataToSend.category_id = categoryIdToDelete;

        fetch(`${wpbAdmin.root}bookify/v1/delete-category`, {
            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 ) {
                this.setState(prevState => {
                    const newSelectedCategories = prevState.selectedCategories.filter(id => id !== categoryId);
                    return {
                        selectedCategories: newSelectedCategories,
                        confirmationDialogOpen: false,
                        confirmationLoading: false,
                        categoryIdToDelete: null,
                        snackbarOpen: true,
                        snackbarMessage: response.message,
                        snackbarType: "success",
                    };
                });
                this.fetchCategoryData();
            } else {
                this.setState({
                    confirmationLoading: false,
                    snackbarOpen: true,
                    snackbarMessage: response.message,
                    snackbarType: "error",
                });
            }
        })
        .catch(error => {
            console.error("Error deleting category:", error);
            this.setState({ confirmationLoading: false });
        })
    };

    render() {
        const { theme, selectedCategories, AddCategoryDialog, snackbarOpen, snackbarMessage, snackbarType, editDialogHandle, confirmationDialogOpen, confirmationLoading, CategoryDataLoading } = this.state;
        const { CategoryData } = this.props;

        return (
            <ThemeProvider theme={theme}>
                <Box component="section" sx={{m:"2em", display:"flex", flexDirection:"column", backgroundColor:"#F8FCFC", p:"23px", border:"1px solid #DDEEEE", borderRadius:"5px", height:"auto", width:"80%"}}>
                    <Grid container direction="column" rowSpacing={5} sx={{width:"100%"}}>
                        {/* <Grid item>
                            <Typography variant="h5" component="div">
                                {__("Selected Categories", "bookify")}
                            </Typography>
                            {selectedCategories.length > 0 ? (
                                <Stack direction="row" spacing={1} flexWrap="wrap" sx={{mt:"2em", p:"10px", alignContent:"flex-start", height:"10em", overflow:"auto"}}>
                                    {selectedCategories.map(categoryId => {
                                        const category = CategoryData.find(cat => cat.id === categoryId);
                                        return (
                                            <Chip variant="wpbkChip" key={categoryId} label={category ? category.category_name : "Unknown"} deleteIcon={<CloseIcon />} onDelete={() => this.handleCategorySelect(categoryId)} />
                                        );
                                    })}
                                </Stack>
                            ) : (
                                <Stack direction="column" spacing={1} flexWrap="wrap" sx={{mt:"2em", p:"10px", alignContent:"center", justifyContent:"center", alignItems:"center", height:"10em", overflow:"auto"}}>
                                    <NoCategory />
                                    <Typography component="div">
                                        {__("No Categories were selected!", "bookify")}
                                    </Typography>
                                </Stack>
                            )}
                        </Grid> */}

                        <Grid item>
                            <Typography variant="h5" component="div">
                                {__("All Categories", "bookify")}
                            </Typography>
                            <Stack direction="column" sx={{mt:"2em", maxHeight:"26em", overflow:"auto", border:"none", backgroundColor:"#F8FCFC"}}>
                                {CategoryDataLoading ? (
                                    Array.from(new Array(5)).map((_, index) => (
                                        <Stack key={index} direction="row" alignItems="center" justifyContent="space-between" sx={{p:"10px", mb:"5px", height:"30px"}}>
                                            <Box sx={{ display: "flex", alignItems: "center" }}>
                                                <Skeleton variant="rectangular" animation="wave" width={20} height={20} />
                                                <Skeleton variant="text" animation="wave" width={150} sx={{ ml: 2 }} />
                                            </Box>
                                            <Box sx={{ display:"flex" }}>
                                                <Skeleton variant="circular" animation="wave" width={25} height={25} />
                                                <Skeleton variant="circular" animation="wave" width={25} height={25} sx={{ ml: 1 }} />
                                            </Box>
                                        </Stack>
                                    ))
                                ) : (
                                    CategoryData.length > 0 ? (
                                        CategoryData.map(category => (
                                            <Stack key={category.id} direction="row" alignItems="center" justifyContent="space-between" sx={{mb:"5px", height:"50px"}}>
                                                <Box sx={{ display: "flex", alignItems: "center" }}>
                                                    <Checkbox
                                                        sx={{
                                                            color: "#30AAA7",
                                                            "&.Mui-checked": {
                                                                color: "#30AAA7",
                                                            }
                                                        }}
                                                        checked={selectedCategories.includes(category.id)}
                                                        onChange={() => this.handleCategorySelect(category.id)}
                                                    />
                                                    <Typography sx={{overflow:"hidden", width:"100%", textOverflow:"ellipsis" }}>{category.category_name}</Typography>
                                                </Box>
                                                <Box sx={{textWrap:"nowrap"}}>
                                                    <IconButton color="primary" onClick={() => openDialog(this.state, this.setState.bind(this), "AddCategoryDialog", category.id)}>
                                                        <ModeIcon />
                                                    </IconButton>
                                                    <IconButton color="error" onClick={() => this.handleDeleteCategory(category.id)}>
                                                        <DeleteIcon />
                                                    </IconButton>
                                                </Box>
                                            </Stack>
                                        ))
                                    ) : (
                                        <Stack direction="column" spacing={1} flexWrap="wrap" sx={{p:"10px", alignContent:"center", justifyContent:"center", alignItems:"center", height:"10em", overflow:"auto"}}>
                                            <NoCategory/>
                                            <Typography component="div">
                                                {__("No Categories were found!", "bookify")}
                                            </Typography>
                                        </Stack>
                                    )
                                )}
                            </Stack>
                        </Grid>

                        <Grid item sx={{ textAlign: "center" }}>
                            <Button variant="wpbkThemeBtn" startIcon={<AddIcon />} onClick={() => openDialog(this.state, this.setState.bind(this), "AddCategoryDialog", null)}>
                                {__("Add Category", "bookify")}
                            </Button>
                            <AddCategory
                                open={AddCategoryDialog}
                                onClose={() => closeDialog(this.state, this.setState.bind(this), "AddCategoryDialog")}
                                fetchCategoryData={this.fetchCategoryData}
                                fetchCategoryById={this.fetchCategoryById}
                                categoryID={editDialogHandle}
                            />
                        </Grid>
                    </Grid>
                    <SnackbarNotice
                        state={this.state}
                        setState={this.setState.bind(this)}
                        open={snackbarOpen}
                        message={snackbarMessage}
                        type={snackbarType}
                    />
                    <ConfirmationDialog
                        open={confirmationDialogOpen}
                        onClose={() => this.setState({ confirmationDialogOpen: false, categoryIdToDelete: null })}
                        onConfirm={this.confirmCategoryDelete}
                        loading={confirmationLoading}
                    />
                </Box>
            </ThemeProvider>
        );
    }
}

export default CategorySection;