import * as React from 'react';
import Paper from '@mui/material/Paper';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TablePagination from '@mui/material/TablePagination';
import TableRow from '@mui/material/TableRow';
import { Box, Collapse, IconButton, Typography } from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';


const columns = [
  {id: '_', label: '',},
  { id: '_id', label: 'Номер заказа', minWidth: 170 },
  {
     id: 'createdAt',
     label: 'Дата',
     minWidth: 100,
     format: (value) => {
        const createdAtFormat = new Date(+value)
        const year = createdAtFormat.getFullYear()
        const month = createdAtFormat.getMonth() < 9 ? "0" + (createdAtFormat.getMonth() + 1) : createdAtFormat.getMonth() + 1
        const day = createdAtFormat.getDate() < 10 ? "0" + (createdAtFormat.getDate()) : createdAtFormat.getDate()
        const hours = createdAtFormat.getHours() < 10 ? "0" + (createdAtFormat.getHours()) : createdAtFormat.getHours()
        const minutes = createdAtFormat.getMinutes() < 10 ? "0" + (createdAtFormat.getMinutes()) : createdAtFormat.getMinutes()
        const createdAtForTable = `${year}.${month}.${day} ${hours}:${minutes} `
        return createdAtForTable
     }
     },
  {
    id: 'total',
    label: 'Сумма',
    minWidth: 170,
    align: 'right',
    format: (value) => value.toLocaleString('en-US'),
  },
  {
    id: 'orderGoods',
    label: 'Количество товаров',
    minWidth: 170,
    align: 'right',
    format: (value) => {

        return Array.isArray(value) ? value?.length : value
        // на момент написания на сайте были битые заказы с orderGoods: null
    },
  },
];



export default function StickyHeadTable({rows = []}) {
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);

  

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(+event.target.value);
    setPage(0);
  };

  return (
    <Paper sx={{ width: '100%', overflow: 'hidden' }}>
      <TableContainer sx={{ maxHeight: 440 }}>
        <Table stickyHeader size="small" aria-label="sticky table">
          <TableHead>
            <TableRow>
              {columns.map((column) => (
                <TableCell
                  key={column.id}
                  align={column.align}
                  style={{ minWidth: column.minWidth }}
                >
                  {column.label}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {rows
              .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
              .map((row) => {
                return (
                  <Row row ={row}></Row>
                );
              })}
          </TableBody>
        </Table>
      </TableContainer>
      <TablePagination
        rowsPerPageOptions={[10, 25, 100]}
        component="div"
        count={rows.length}
        rowsPerPage={rowsPerPage}
        page={page}
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}
      />
    </Paper>
  );
}
// єто біло в табе боди стр 83
// <TableRow hover role="checkbox" tabIndex={-1} key={row._id}>
//                    {columns.map((column) => {
//                        const value = row[column.id]
//                        {/* console.log('value', value) */}
                     
//                        return (
//                          <TableCell key={column.id} align={column.align}>
//                              {column.format ? column.format(value) : value}
//                          </TableCell>
//                        );
//                      })}
//                    </TableRow> 

function Row(props) {
  const { row } = props;
  const [open, setOpen] = React.useState(false);
 

  return (
    <React.Fragment>
      <TableRow sx={{ '& > *': { borderBottom: 'unset' } }}>
        <TableCell>
          <IconButton
            aria-label="expand row"
            size="small"
            onClick={() => setOpen(!open)}
          >
            {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
          </IconButton>
        </TableCell>
        <TableCell component="th" scope="row">
          {row._id}
        </TableCell>
        <TableCell align="right">{row. createdAt}</TableCell>
        <TableCell align="right">{row.total}</TableCell>
      </TableRow>
      <TableRow>
        <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}>
          <Collapse in={open} timeout="auto" unmountOnExit>
            <Box sx={{ margin: 1 }}>
              <Typography variant="h6" gutterBottom component="div">
                Подробности заказа
              </Typography>
              <Table size="small" aria-label="purchases">
                <TableHead>
                  <TableRow>
                    <TableCell>ID товара</TableCell>
                    <TableCell>Название</TableCell>
                    <TableCell align="right">Количество (шт)</TableCell>
                    <TableCell align="right">Цена (грн.)</TableCell>
                    <TableCell align="right">Сумма (грн.)</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>

                {row.orderGoods ? 
                  row.orderGoods.map((orderGood) => {
                    console.log('orderGood true', orderGood)
                    if(orderGood){
                      return (
                        <TableRow key={orderGood._id}>
                        <TableCell component="th" scope="row">
                        {orderGood?._id}
                      </TableCell>
                      <TableCell >
                        {orderGood?.goodName || ''}
                      </TableCell>
                      <TableCell align="right">
                        {orderGood?.count}
                      </TableCell>
                      <TableCell align="right">
                        {orderGood?.price}
                      </TableCell>
                      <TableCell align="right">
                        {orderGood?.total}
                      </TableCell>
                        </TableRow>
                      )
                    }
                    } )
                :
                null 
                }

                </TableBody>
              </Table>
            </Box>
          </Collapse>
        </TableCell>
      </TableRow>
    </React.Fragment>
  );
}