import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import {
    Dialog, DialogTitle, DialogContent, DialogActions, Box, Button,
    Divider, IconButton, Grid, FormControl, TextField, Typography
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import {SnackbarNotice} from "../../functions";
import LoadingButton from "@mui/lab/LoadingButton";

class AddCategory extends Component { 
    state = { 
        addFormData: { categoryName: "", categorySlug: "" },
        editFormData: { categoryName: "", categorySlug: "" },
        errors: { categoryName: false, categorySlug: false },
        snackbarOpen: false,
        snackbarMessage: "",
        snackbarType: "success",
        loading: false,
        theme: createTheme({
            typography: {
                wpbkThemeLabel: {
                    color: "#042626",
                    fontSize: "15px",
                    fontWeight: "500",
                    paddingBottom: "5px",
                }
            },
            components: {
                MuiButton: {
                    variants: [
                        {
                            props: { variant: "wpbkThemeModalBtn" },
                            style: {
                                borderColor: "none",
                                backgroundColor: "#036666",
                                color: "#FFFFFF",
                                textTransform: "capitalize",
                                height: "40px",
                                "&:hover": {
                                    backgroundColor: "#025151",
                                    color: "#FFFFFF"
                                },
                                "&.Mui-disabled": {
                                    color: "#FFFFFF",
                                    opacity: 0.7,
                                },
                                "& .MuiLoadingButton-loadingIndicator": {
                                    color: "#FFFFFF",
                                }
                            },
                        },
                        {
                            props: { variant: "wpbkCancelbtn"},
                            style: {
                                textTransform: "capitalize",
                                height: "40px",
                                color: "#036666",
                                "&:hover": {
                                    backgroundColor: "#DDEEEE",
                                },
                            }
                        }
                    ]
                },
            }
        })
    };

    handleClose = () => this.props.onClose && this.props.onClose();

    componentDidUpdate(prevProps) {
        if (this.props.categoryID && prevProps.categoryID !== this.props.categoryID) {
            this.loadCategoryData(this.props.categoryID);
        }
    }

    handleInputChange = ({ target: { name, value } }) => {
        const formState = this.props.categoryID ? "editFormData" : "addFormData";
        this.setState(prevState => ({
            [formState]: { ...prevState[formState], [name]: value },
            errors: { ...prevState.errors, [name]: false }
        }));
    };

    loadCategoryData = (categoryId) => {
        const category = this.props.fetchCategoryById(categoryId);
        if (category) {
            this.setState({ 
                editFormData: { categoryName: category.category_name, categorySlug: category.category_slug } 
            });
        }
    };

    handleCategorySubmit = () => {
        const { addFormData, editFormData } = this.state;
        const { categoryID, fetchCategoryData } = this.props;
        const dataToSend = {};
        
        const currentForm = categoryID ? editFormData : addFormData;
        
        const errors = {
            categoryName: !currentForm.categoryName,
            categorySlug: !currentForm.categorySlug
        };

        this.setState({ errors });

        if (errors.categoryName || errors.categorySlug) {
            return;
        }

        this.setState({ loading: true });

        if (categoryID) {
            dataToSend.category_id = categoryID;
            dataToSend.category_name = editFormData.categoryName; 
            dataToSend.category_slug = editFormData.categorySlug.toLowerCase().replace(/ /g, "-");
        } else {
            dataToSend.category_name = addFormData.categoryName; 
            dataToSend.category_slug = addFormData.categorySlug.toLowerCase().replace(/ /g, "-");
        }

        const endpoint = categoryID ? `${wpbAdmin.root}bookify/v1/update-category` : `${wpbAdmin.root}bookify/v1/add-category`;
        fetch(endpoint, { 
            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({ 
                    addFormData: { 
                        categoryName: "", 
                        categorySlug: "" 
                    },
                    errors: { categoryName: false, categorySlug: false },
                    snackbarOpen: true,
                    snackbarMessage: response.message,
                    snackbarType: "success",
                    loading: false
                });
                this.handleClose()
                fetchCategoryData();
            } else {
                this.setState({ 
                    snackbarOpen: true, 
                    snackbarMessage: response.message, 
                    snackbarType:  "error",
                    loading: false
                });
            }
        })
        .catch(error => {
            console.error("Error:", error);
            this.setState({ loading: false });
        })
    };

    render() { 
        const { open, categoryID } = this.props;
        const { theme, addFormData, editFormData, errors, snackbarOpen, snackbarMessage, snackbarType, loading } = this.state;
        const currentForm = categoryID ? editFormData : addFormData;

        return (
            <>  
                <ThemeProvider theme={theme}>
                    <Dialog onClose={this.handleClose} open={open} fullWidth maxWidth={"sm"} sx={{height:"80%", padding:"4% 0%"}}>
                        <DialogTitle>
                            {categoryID ? __("Edit Category", "bookify") : __("Add Category", "bookify")}
                            <IconButton 
                                onClick={this.handleClose}
                                sx={{
                                    position: "absolute",
                                    right: 8,
                                    top: 8,
                                    color: (theme) => theme.palette.grey[500],
                                    "&:hover": {
                                        backgroundColor: "#DDEEEE",
                                    },
                                }}
                            >
                                <CloseIcon sx={{fontSize:"1rem"}} />
                            </IconButton>
                        </DialogTitle>

                        <Divider sx={{borderColor:"#DDEEEE"}} />

                        <DialogContent>
                            <Box component="form">
                                <Grid container spacing={4} direction="column">
                                    <Grid item>
                                        <FormControl fullWidth>
                                            <Typography variant="wpbkThemeLabel" component="label" htmlFor="category-name">
                                                {__("Category Name ", "bookify")}
                                                <span style={{color:"#A61616"}}>*</span>
                                            </Typography>
                                            <TextField 
                                                id="category-name"
                                                required
                                                error={errors.categoryName}
                                                type="text"
                                                name="categoryName" 
                                                value={currentForm.categoryName}
                                                onChange={this.handleInputChange} 
                                                sx={{
                                                    borderRadius: "5px",
                                                    justifyContent: "center",
                                                    "& fieldset": {
                                                        border: "none",
                                                    },
                                                    "& .MuiOutlinedInput-root": {
                                                        mt: "0px",
                                                        height: "43px",
                                                        border: "1px solid",
                                                        borderColor: errors.categoryName ? "error.main" : "#BFD4D4",
                                                    },
                                                    "& .MuiInputBase-input": {
                                                        padding: "0px 14px"
                                                    }
                                                }}
                                            />
                                        </FormControl>
                                    </Grid>
                                    <Grid item>
                                        <FormControl fullWidth>
                                            <Typography variant="wpbkThemeLabel" component="label" htmlFor="category-slug">
                                                {__("Category Slug ", "bookify")}
                                                <span style={{color:"#A61616"}}>*</span>
                                            </Typography>
                                            <TextField 
                                                id="category-slug"
                                                required
                                                error={errors.categorySlug}
                                                type="text"
                                                name="categorySlug" 
                                                value={currentForm.categorySlug}
                                                onChange={this.handleInputChange}
                                                sx={{
                                                    borderRadius: "5px",
                                                    justifyContent: "center",
                                                    "& fieldset": {
                                                        border: "none",
                                                    },
                                                    "& .MuiOutlinedInput-root": {
                                                        mt: "0px",
                                                        height: "43px",
                                                        border: "1px solid",
                                                        borderColor: errors.categorySlug ? "error.main" : "#BFD4D4",
                                                    },
                                                    "& .MuiInputBase-input": {
                                                        padding: "0px 14px"
                                                    }
                                                }}
                                            />
                                        </FormControl>
                                    </Grid>
                                </Grid>
                            </Box>
                        </DialogContent>

                        <Divider sx={{borderColor:"#DDEEEE"}} />

                        <DialogActions sx={{m:2}}>
                            <Button variant="wpbkCancelbtn" onClick={this.handleClose}>
                                {__("Cancel", "bookify")}
                            </Button>
                            <LoadingButton variant="wpbkThemeModalBtn" onClick={this.handleCategorySubmit} loading={loading}>
                                {categoryID ? __("Update Category", "bookify") : __("Add Category", "bookify")}
                            </LoadingButton>
                        </DialogActions>
                    </Dialog>
                </ThemeProvider>
                <SnackbarNotice
                    state={this.state}
                    setState={this.setState.bind(this)}
                    open={snackbarOpen}
                    message={snackbarMessage}
                    type={snackbarType}
                />
            </>
        );
    }
}

export default AddCategory;
