import React from 'react';
import PropTypes from 'prop-types';
import { lighten, withStyles, makeStyles } from '@material-ui/core/styles';
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 TableHead from '@material-ui/core/TableHead';
import TableFooter from '@material-ui/core/TableFooter';
import TablePagination from '@material-ui/core/TablePagination';
import TableRow from '@material-ui/core/TableRow';
import TableSortLabel from '@material-ui/core/TableSortLabel';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import IconButton from '@material-ui/core/IconButton';
import Tooltip from '@material-ui/core/Tooltip';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FilterListIcon from '@material-ui/icons/FilterList';
import Toolbar from '@material-ui/core/Toolbar';
import clsx from 'clsx';


function descendingComparator(a, b, orderBy) {
  //console.log('dc',orderBy, a[orderBy], b[orderBy])
  const aItem = (typeof a[orderBy] === 'undefined' || isNaN(parseInt(a[orderBy][0]))) ? a[orderBy] : parseFloat(a[orderBy].replace(',', '')),
        bItem = (typeof b[orderBy] === 'undefined' || isNaN(parseInt(b[orderBy][0]))) ? b[orderBy] : parseFloat(b[orderBy].replace(',', ''))
  if (bItem < aItem) {
    return -1;
  }
  if (bItem > aItem) {
    return 1;
  }
  return 0;
}

function getComparator(order, orderBy) {
  return order === 'desc'
    ? (a, b) => descendingComparator(a, b, orderBy)
    : (a, b) => -descendingComparator(a, b, orderBy);
}

function stableSort(array, comparator) {
  //console.log('statblesort', array)
  const stabilizedThis = array.map((el, index) => [el, index]);
  stabilizedThis.sort((a, b) => {
    //console.log('sortcheck', a[1], b[1])
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });
  return stabilizedThis.map((el) => el[0]);
}

function EnhancedTableHead(props) {
  const { classes, order, orderBy, rowCount, onRequestSort, headCells, colGroups, align } = props;
  const createSortHandler = (prop) => (ev) => {
    onRequestSort(ev, prop);
  };

  return (
    <TableHead>
    {colGroups &&
      <TableRow className={classes.row}>
        {colGroups.map((colGroup, idx) => {
          return (
            <TableCell
              key={idx}
              component="th"
              align="center"
              className={classes.cell}
              colSpan={colGroup.cols.length}
            >
              {colGroup.title}
            </TableCell>
          )
        })}
      </TableRow>
    }
      <TableRow className={classes.row}>
        {headCells.map((headCell, idx) => (
          <TableCell
            key={headCell.id}
            align={align ? align : headCell.numeric ? 'right' : 'left'}
            sortDirection={orderBy === headCell.id ? order : false}
            title={headCell.title}
            className={classes.cell}
          >
            <TableSortLabel
              active={orderBy === headCell.id}
              direction={orderBy === headCell.id ? order : 'asc'}
              onClick={createSortHandler(headCell.id)}
            >
              {headCell.label}
              {orderBy === headCell.id ? (
                <span className={classes.visuallyHidden}>
                  {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                </span>
              ) : null}
            </TableSortLabel>
          </TableCell>
        ))}
      </TableRow>
    </TableHead>
  );
}

EnhancedTableHead.propTypes = {
  classes: PropTypes.object.isRequired,
  onRequestSort: PropTypes.func.isRequired,
  order: PropTypes.oneOf(['asc', 'desc']).isRequired,
  orderBy: PropTypes.string.isRequired,
  rowCount: PropTypes.number.isRequired,
  headCells: PropTypes.array.isRequired
};

const useToolbarStyles = makeStyles((theme) => ({
  root: {
    paddingLeft: theme.spacing(2),
    paddingRight: theme.spacing(1),
  },
  highlight:
    theme.palette.type === 'light'
      ? {
          color: theme.palette.secondary.main,
          backgroundColor: lighten(theme.palette.secondary.light, 0.85),
        }
      : {
          color: theme.palette.text.primary,
          backgroundColor: theme.palette.secondary.dark,
        },
  title: {
    flex: '1 1 100%',
    textTransform: 'capitalize'
  },
}));

const EnhancedTableToolbar = (props) => {
  const classes = useToolbarStyles();

  return (
    <Toolbar
      style={{paddingLeft: 32}}
      className={clsx(classes.root, {
        [classes.highlight]: false,
      })}
    >
      <Typography className={classes.title} variant="h6" id="tableTitle" component="div">
        {props.title}
      </Typography>
      
      <Tooltip title="Filter list">
        <IconButton aria-label="filter list">
          <FilterListIcon />
        </IconButton>
      </Tooltip>
      
    </Toolbar>
  );
};



const styles = theme => ({
  root: {
    width: '100%',
  },
  table: {
    minWidth: 750
    
  },
  row: {
    height: 56
  },
  cell: {
    padding: '0 16px',
    lineHeight: 1
  },
  container: {
    maxHeight: 350
  },
  visuallyHidden: {
    border: 0,
    clip: 'rect(0 0 0 0)',
    height: 1,
    margin: -1,
    overflow: 'hidden',
    padding: 0,
    position: 'absolute',
    top: 20,
    width: 1,
  },
});


class EnhancedTable extends React.Component {
  constructor() {
    super();
    this.state = {
      order: 'desc',
      orderBy: '',
      dense: false
    }
    
    this.handleRequestSort = this.handleRequestSort.bind(this);
  }

  handleRequestSort(ev, prop) {
    const state = this.state;
    const isDesc = state.orderBy === prop && state.order === 'desc';
    this.setState({orderBy: prop, order: isDesc ? 'asc' : 'desc'});
  }

  render() {
    //const state = this.state;
    const {
      order, orderBy, dense
    } = this.state;
    const { classes, headCells, rows, title, footRow, colGroups, align } = this.props;
    
    const stickyRows = rows.map(row => (row.hasOwnProperty('date') && row.date.hasOwnProperty('props') && row.date.props.children === 'DATE'));

    console.log('stickyrows', stickyRows);
  
    return (
      <div className={classes.root}>
        <Paper>
        {false && <EnhancedTableToolbar title={title} /> }
          <TableContainer className={classes.container}>
            <Table
              stickyHeader
              className={classes.table + ' enhanced-table'}
              aria-labelledby="tableTitle"
              size={dense ? 'small' : 'medium'}
              aria-label="enhanced table"
            >
              {colGroups &&
                colGroups.map((colGroup, idx1) => {
                  return (
                    <colgroup key={idx1} className="Table__Colgroup">
                      {[...colGroup.cols].map((col, idx2) => {
                        //console.log('col', idx1, idx2, col);
                        return (
                          <col key={idx2} />
                        )
                      })}
                    </colgroup>
                  )
                })
              }
              <EnhancedTableHead
                classes={classes}
                order={order}
                orderBy={orderBy}
                onRequestSort={this.handleRequestSort}
                rowCount={rows.length}
                headCells={headCells}
                colGroups={colGroups}
                align={align}
              />
              <TableBody>
                {stableSort(rows, getComparator(order, orderBy))
                  .map((row, rowI) => {
                    return (
                      <TableRow
                        hover
                        tabIndex={-1}
                        key={rowI}
                        className={classes.row}
                      >
                        {Object.keys(row).map((key, colI) => {
                          return (colI === 0) ? (
                            <TableCell
                              key={colI}
                              component="th"
                              scope="row"
                              align={align ? align : 'left'}
                              className={stickyRows[rowI] ? classes.cell + ' MuiTableCell-stickyHeader' : classes.cell}
                            >
                              {row[key]}
                            </TableCell>
                          ) : (
                            <TableCell
                              key={colI}
                              component="td"
                              align={align ? align : 'right'}
                              className={stickyRows[rowI] ? classes.cell + ' MuiTableCell-stickyHeader' : classes.cell}
                            >
                              {row[key]}
                            </TableCell>
                          );
                        })}
                      </TableRow>
                    );
                  })}
              </TableBody>
              {footRow &&
                <TableFooter>
                  <TableRow
                    hover
                    tabIndex={-1}
                    className={classes.row}
                  >
                    {Object.keys(footRow).map((key, idx) => {
                      return (
                        <TableCell
                          key={idx}
                          component={(idx === 0) ? 'th' : 'td'}
                          scope={(idx === 0) ? 'row' : null}
                          align={align ? align : (idx === 0) ? 'left' : 'right'}
                          className={classes.cell}
                        >
                          {footRow[key]}
                        </TableCell>
                      );
                    })}
                  </TableRow>
                </TableFooter>
              }
            </Table>
          </TableContainer>
        </Paper>
      </div>
    );
  }
}

export default withStyles(styles, { withTheme: true })(EnhancedTable);