import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import {
    Paper, Typography, TableContainer, Table, TableHead, 
    TableRow, TableCell, TableSortLabel, TableBody,
    TablePagination, Avatar, IconButton, Box, Skeleton
} from "@mui/material";
import ModeIcon from "@mui/icons-material/Mode";
import DeleteIcon from "@mui/icons-material/Delete";
import { 
    handleRequestSort, handleChangePage, handleChangeRowsPerPage, openDialog 
} from "../../functions";
import { SnackbarNotice, ConfirmationDialog } from "../../functions";

class StaffTable extends Component { 

    state = {
        snackbarOpen: false,
        snackbarMessage: "",
        snackbarType: "success",
        confirmationDialogOpen: false,
        confirmationLoading: false,
        StaffIdToDelete: null
    }

    componentDidMount() {
        let { headCells } = this.props;

        headCells = window.wp.hooks.applyFilters("bookify_staff_table_add_columns", headCells);
        this.props.setState({ headCells });
    }

    handleStaffDelete = (staffId) => {
        this.setState({ confirmationDialogOpen: true, StaffIdToDelete: staffId });
    };

    ConfirmationStaffDelete = () => {
        const { StaffIdToDelete } = this.state;
        this.setState({ confirmationLoading: true });

        const dataToSend = {};
        dataToSend.staff_id = StaffIdToDelete;

        fetch(`${wpbAdmin.root}bookify/v1/delete-staff`, {
            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({ 
                    confirmationDialogOpen: false,
                    confirmationLoading: false,
                    StaffIdToDelete: null,
                    snackbarOpen: true,
                    snackbarMessage: response.message,
                    snackbarType: "success",
                });
                this.props.fetchStaffData();
            } 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 { snackbarOpen, snackbarMessage, snackbarType, confirmationDialogOpen, confirmationLoading } = this.state;
        const { state, setState, headCells, TableData, totalCount, pageSize, page, orderBy, order, isStaff, dataLoading } = this.props;

        return (
            <>
                <Paper sx={{boxShadow:"none", border:"1px solid #DDEEEE", borderRadius:"4px"}}>
                    <TableContainer>
                        <Table>
                            <TableHead>
                                <TableRow>
                                    {headCells.sort((a, b) => a.priority - b.priority).map((headCell) => (
                                        <TableCell
                                            key={headCell.id}
                                            align="left"
                                            sortDirection={orderBy === headCell.id ? order : false}
                                            sx={{borderBottom: "1px solid #CDE0E0", width:headCell.id === "action" ? "6em" : "unset"}}
                                        >
                                            {headCell.id === "action" ? (
                                                <Typography variant="span">{headCell.label}</Typography>
                                            ) : (
                                                <TableSortLabel
                                                    active={orderBy === headCell.id}
                                                    direction={orderBy === headCell.id ? order : "desc"}
                                                    onClick={(event) => handleRequestSort(state, setState, headCell.id)}
                                                >
                                                    {headCell.label}
                                                </TableSortLabel>
                                            )}
                                        </TableCell>
                                    ))}
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {dataLoading ? (
                                    Array.from({ length: 5 }).map((_, index) => (
                                        <TableRow key={index}>
                                            {headCells.map((headCell) => (
                                                <TableCell key={headCell.id} align="left" sx={{borderBottom: "1px solid #CDE0E0"}}>
                                                    <Skeleton animation="wave" variant="text" width="80%" />
                                                </TableCell>
                                            ))}
                                        </TableRow>
                                    ))
                                ) : TableData.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={headCells.length} align="center" sx={{borderBottom: "1px solid #CDE0E0", height:"36px"}}>
                                            {__("No records to display", "bookify")}
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    TableData.map((row) => (
                                        <TableRow hover key={row.id} >
                                            {headCells.sort((a, b) => a.priority - b.priority).map((headCell) => (
                                                <TableCell key={headCell.id} align="left" sx={{borderBottom: "1px solid #CDE0E0"}}>
                                                    {headCell.id === "staff_name" ? (
                                                        <Typography 
                                                            sx={{
                                                                display: "flex",
                                                                alignItems: "center",
                                                                flexDirection: "row",
                                                                justifyContent: "left",
                                                            }}
                                                        >
                                                            <Avatar 
                                                                src={row.staff_img ? row.staff_img : undefined}
                                                                sx={{
                                                                    fontSize:"1rem",
                                                                    width:"35px",
                                                                    height:"35px",
                                                                    mr:"10px"
                                                                }}
                                                            />
                                                            {row[headCell.id]}
                                                        </Typography>
                                                    ) : headCell.id === "action" ? (
                                                        <Box sx={{textWrap:"nowrap", width:"100%"}}>
                                                            <IconButton 
                                                                color="success"
                                                                onClick={() => {
                                                                    openDialog(state, setState, "AddStaffDialog", row.id);
                                                                }}
                                                                sx={{padding:"6px"}}
                                                            >
                                                                <ModeIcon />
                                                            </IconButton>
                                                            { ! isStaff && (
                                                                <>
                                                                    <IconButton 
                                                                        color="error"
                                                                        onClick={(event) => {
                                                                            event.stopPropagation();
                                                                            this.handleStaffDelete(row.id);
                                                                        }}
                                                                        sx={{padding:"6px"}}
                                                                    >
                                                                        <DeleteIcon />
                                                                    </IconButton>
                                                                </>
                                                            )}
                                                        </Box>
                                                    ) : (
                                                        row[headCell.id]
                                                    )}
                                                </TableCell>
                                            ))}
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    </TableContainer>
                    <TablePagination
                        component="div"
                        count={totalCount}
                        rowsPerPage={pageSize}
                        page={page}
                        onPageChange={(event, newPage) => handleChangePage(state, setState, this.props.fetchStaffData, newPage)}
                        onRowsPerPageChange={(event) => handleChangeRowsPerPage(state, setState, this.props.fetchStaffData, event)}
                    />
                </Paper>
                <SnackbarNotice
                    state={this.state}
                    setState={this.setState.bind(this)}
                    open={snackbarOpen}
                    message={snackbarMessage}
                    type={snackbarType}
                />
                <ConfirmationDialog
                    open={confirmationDialogOpen}
                    onClose={() => this.setState({ confirmationDialogOpen: false, StaffIdToDelete: null })}
                    onConfirm={this.ConfirmationStaffDelete}
                    loading={confirmationLoading}
                />
            </>
        )
    }
}

export default StaffTable;