import React from "react";

import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TablePagination from "@material-ui/core/TablePagination";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";
import Checkbox from "@material-ui/core/Checkbox";
import Spin from "@/commons/components/Material.Ui/Spin";
import { CLOUDE } from '@/commons/utils/constants';
import EnhancedTableToolbarComponent from "./Table/EnhancedTableToolbar"
import EnhancedTableHeadComponent from "./Table/EnhancedTableHead"
import { getComparator, stableSort, useStyles } from "./Table/function";
import ActionsComponent from "./Table/ActionsComponent"
import { useEffect } from "react";
import Tooltip from '@material-ui/core/Tooltip';

export default function EnhancedTable(props) {
  const classes = useStyles();
  const [order, setOrder] = React.useState("asc");
  const [orderBy, setOrderBy] = React.useState("");
  const { headCells, rows, footer = true, elevation1, tableStyle, tableContainerStyle, stickyheader, TableHeadClasses, onRowClick, defaultRow, minHeight = '', borderBottom = '', onDoubleClick, bodyTableCellStyle, headTableCellStyle, cancelHover,
    load, size, checkboxData, rowsPerPage = 10, initSelected, page = 0, changePage = function () { }, toolbar, count, param, disabledparam = "id", headTableCellCheckbox, RowHeight = '', CellWidth = '', rowHover, TableNodataPadding = '', TableNodataLineHeight = '' } = props;
  const [selected, setSelected] = React.useState(initSelected || []);
  const [rowsPerPageOptions, setRowsPerPageOptions] = React.useState(initSelected || [5, 10, 20, 50, { value: -1, label: 'All' }]);
  const [spin, setSpin] = React.useState(false)
  const [onRow, setOnRow] = React.useState('')

  useEffect(() => {
    setOnRow(defaultRow)
  }, [defaultRow])

  const onRowClickDefault = (value) => {
    setOnRow(value)
    onRowClick(value)
  }

  const handleRequestSort = (event, property) => {
    const isAsc = orderBy === property && order === "asc";
    setOrder(isAsc ? "desc" : "asc");
    setOrderBy(property);
  };

  const handleSelectAllClick = (event) => {
    if (event.target.checked) {
      const newSelecteds = rows.map((n) => n[param || 'id']);
      setSelected(newSelecteds);
      checkboxData(newSelecteds);
      return;
    }
    setSelected([]);
    checkboxData([]);
  };
  React.useEffect(() => {

    setSpin(load)
  }, [load]);
  const handleClick = (event, name) => {
    const selectedIndex = selected.indexOf(name);
    let newSelected = [];

    if (selectedIndex === -1) {
      newSelected = newSelected.concat(selected, name);
    } else if (selectedIndex === 0) {
      newSelected = newSelected.concat(selected.slice(1));
    } else if (selectedIndex === selected.length - 1) {
      newSelected = newSelected.concat(selected.slice(0, -1));
    } else if (selectedIndex > 0) {
      newSelected = newSelected.concat(
        selected.slice(0, selectedIndex),
        selected.slice(selectedIndex + 1)
      );
    }
    checkboxData(newSelected)
    setSelected(newSelected);
  };

  const handleOnPageChange = (event, newPage) => {
    changePage(newPage, rowsPerPage);
  };

  const handleChangeRowsPerPage = (event) => {
    changePage(0, parseInt(event.target.value, 10));
  };

  const isSelected = (name) => selected.indexOf(name) !== -1;

  const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage);

  return (
    <div className={classes.root}>
      <Paper className={classes.paper} classes={{ elevation1: elevation1 || classes.elevation1 }} >
        <Spin spin={spin} />
        {toolbar && toolbar}
        <TableContainer style={{ ...tableContainerStyle }}>
          <Table stickyHeader={stickyheader || false} className={classes.table} style={{ ...tableStyle }} aria-labelledby="tableTitle" size={size || "medium"} aria-label="cloudam table header" >
            <EnhancedTableHeadComponent
              classes={classes}
              {...props}
              numSelected={selected.length}
              headTableCellCheckbox={headTableCellCheckbox}
              headTableCell={headTableCellStyle}
              order={order}
              orderBy={orderBy}
              onSelectAllClick={handleSelectAllClick}
              onRequestSort={handleRequestSort}
              rowCount={rows.length}
              headCells={headCells || []}
            />
            <TableBody>
              {
                (rows.length === 0 && !load) && <TableRow>
                  <TableCell
                    colSpan={headCells.filter(k => k.id === "checkbox").length === 0 ? headCells.length : headCells.length + 1}
                    className={classes.TypographyStyle}
                    style={{ minHeight: minHeight, height: minHeight, borderBottom: borderBottom, padding: TableNodataPadding, lineHeight: TableNodataLineHeight }}
                  >
                    No Data
                  </TableCell>
                </TableRow>
              }
              {stableSort(rows, getComparator(order, orderBy)).slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row, index) => {
                const isItemSelected = isSelected(row[param || "id"]);
                const labelId = `enhanced-table-checkbox-${index}`;
                return (
                  <TableRow
                    hover={rowHover ? false : (row[disabledparam || "enabled"] ? true : false)}
                    onClick={(event) => {
                      if (!row[disabledparam]) return;
                      onRowClick && onRowClickDefault(row[param || "id"])
                      headCells.filter(k => k.id === "checkbox").length > 0 && handleClick(event, row[param || "id"])
                    }}
                    onDoubleClick={() => {
                      onDoubleClick && onDoubleClick(row)
                    }}
                    style={{
                      height: RowHeight,
                      border: onRow === row[param || "id"] ? !row[disabledparam] ? "" : '1px solid #136EFA' : "",
                      backgroundColor: onRow === row[param || "id"] ? !row[disabledparam] ? "rgba(255, 255, 255, 0.4)" : "rgba(19, 110, 250, 0.1)" : "",
                      cursor: props.cursor ? (row[props.cursor] ? "pointer" : "auto") : (onRowClick ? !row[disabledparam] ? "no-drop" : "pointer" : "auto"),
                      opacity: !row[disabledparam] ? 0.3 : 1
                    }}
                    classes={{
                      root: cancelHover && classes.cancelHoverStyle
                    }}
                    role="checkbox"
                    aria-checked={isItemSelected}
                    tabIndex={-1}
                    key={row[param || "id"]}
                    selected={isItemSelected}
                  >
                    {
                      headCells.filter(k => k.id === "checkbox").length > 0 && <TableCell padding="checkbox">
                        <Checkbox color={"primary"} checked={isItemSelected} inputProps={{ "aria-labelledby": labelId }} />
                      </TableCell>
                    }
                    {
                      headCells.map((item, k) => {
                        let subscript = rows.findIndex((e) => e[item.id] === 'merge')
                        if (index !== subscript && row[item.id] === 'merge') return null
                        return (
                          <TableCell key={k} component="th" id={labelId + k}
                            style={{ width: CellWidth, textAlign: item.numeric ? "right" : "left", paddingRight: item.sort && item.numeric ? "40px" : "", boxSizing: "border-box" }}
                            scope="row"
                            rowSpan={(row[item.id] === 'merge') ? (rows.length - (index)) : 1}
                            padding={item.disablePadding ? "none" : "normal"}
                            classes={{
                              body: bodyTableCellStyle || classes.bodyTableCell,
                            }}
                          > {row[item.id] === 'merge' ? ((item.id === 'parallelFileSystem' && rows[0].parallelFileSystem === "merge") ? CLOUDE.chargesText16 : "") : row[item.id]}</TableCell>
                        )
                      })
                    }
                  </TableRow>
                );
              })}
              {/* {emptyRows > 0 && (
                <TableRow style={{ height: (dense ? 33 : 53) * emptyRows }}>
                  <TableCell colSpan={6} />
                </TableRow>
              )} */}
            </TableBody>
          </Table>
        </TableContainer>
        {
          footer && <TablePagination
            rowsPerPageOptions={rowsPerPageOptions}
            component="div"
            count={count || rows.length}
            rowsPerPage={rowsPerPage}
            page={page}
            ActionsComponent={ActionsComponent}
            onChangePage={handleOnPageChange}
            onChangeRowsPerPage={handleChangeRowsPerPage}
          />
        }

      </Paper>
    </div>
  );
}
