import * as React from "react";
import Box from "@mui/material/Box";
import Paper from "@mui/material/Paper";
import TableContainer from "@mui/material/TableContainer";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableRow from "@mui/material/TableRow";
import TableCell from "@mui/material/TableCell";
import TablePagination from "@mui/material/TablePagination";
import {getComparator} from "../core/getComparator";
import {EnhancedTableToolbar} from "./EnhancedTableToolbar";
import {EnhancedTableHead} from "./EnhancedTableHead";

export default function EnhancedTable({name, rows, cells, handleSelect, filterField, filterEqual, filterValue}) {
    //сортировка убывание/возрастание
    const [order, setOrder] = React.useState('desc');
    //По какому полю сортируем
    const [orderBy, setOrderBy] = React.useState('id');
    //выбранная страница
    const [page, setPage] = React.useState(0);
    //количество элементов на странице
    const [rowsPerPage, setRowsPerPage] = React.useState(10);

    const handleRequestSort = (event, property) => {
        const isAsc = orderBy === property && order === 'asc';
        setOrder(isAsc ? 'desc' : 'asc');
        setOrderBy(property);
    };
    const handleChangePage = (event, newPage) => {
        setPage(newPage);
    };
    const handleChangeRowsPerPage = (event) => {
        setRowsPerPage(parseInt(event.target.value, 10));
        setPage(0);
    };
    const getTableValue = (obj, index) => {
        let indexArr = index.split(".");
        let object = obj;
        for (let i of indexArr) {
            object = object[i];
        }
        return object;
    }

    const visibleRows = React.useMemo(() =>
            [...rows]
                .filter((row) => {
                    if (!filterField) {
                        return true;
                    }
                    for (let field of filterField) {
                        for (let value of filterValue) {
                            let eq = (row[field] === value) === filterEqual;
                            if (!eq) {
                                return false;
                            }
                        }
                    }
                    return true;
                })
                .sort(getComparator(order, orderBy))
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage),
        [order, orderBy, page, rowsPerPage, rows, filterEqual, filterField, filterValue],
    );

    const renderTable = (row) => {
        // const isItemSelected = selected.includes(row.id);
        const isItemSelected = false;
        return (
            <TableRow hover onClick={() => handleSelect(row)} role="checkbox"
                      aria-checked={isItemSelected} tabIndex={-1} key={row.id} selected={isItemSelected}
                      sx={{cursor: 'pointer'}}>
                {cells.map((cell) => {
                    return (
                        <TableCell key={cell.id} sx={{maxWidth: cell.width}}>{getTableValue(row, cell.id)}</TableCell>
                    )
                })}
            </TableRow>
        );
    }
    const emptyRow = () => {
        return (
            <TableRow>
                <TableCell colSpan={cells.length}>
                    Нет заказов
                </TableCell>
            </TableRow>
        )
    }

    return (
        <Box sx={{width: '100%'}}>
            <Paper sx={{width: '100%', mb: 2}}>
                <EnhancedTableToolbar numSelected={0} name={name}/>
                <TableContainer>
                    <Table sx={{width: 'calc(100% - 30px)'}} aria-labelledby="tableTitle" size="medium">
                        <EnhancedTableHead numSelected={0} order={order} orderBy={orderBy}
                                           onRequestSort={handleRequestSort}
                                           rowCount={rows.length} cells={cells}/>
                        <TableBody>
                            {visibleRows.map((row) => renderTable(row))}
                            {visibleRows.length === 0 && emptyRow()}
                        </TableBody>
                    </Table>
                </TableContainer>
                <TablePagination rowsPerPageOptions={[5, 10, 25]} component="div" count={visibleRows.length}
                                 rowsPerPage={rowsPerPage}
                                 page={page} onPageChange={handleChangePage}
                                 onRowsPerPageChange={handleChangeRowsPerPage}/>
            </Paper>
        </Box>
    );
}