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';
import { useGetOrdersCountQuery, useGetUserOrders2Query, useGetUserOrdersQuery } from '../store/categoriesApi';
import { useSelector } from 'react-redux';





function TimestampConv(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
}


export default function StickyHeadTable() {
  const userId = useSelector(state => state.auth.user?.sub.id)
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const {data: OrderCount} = useGetOrdersCountQuery()
  const count = OrderCount?.OrderCount || 1
  const orders = useGetUserOrdersQuery({userId, limit: rowsPerPage, skip: page * rowsPerPage, sort: {_id: -1}})
  const rows = orders?.data ? Object.values(orders.data)[0] : []
  

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

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

  return (
    <Paper sx={{ width: '100%', overflow: 'hidden', display: "flex", flexDirection: "column", alignItems: "center" }}>
      <Typography variant='h4'>История заказов</Typography>
      <TablePagination
        rowsPerPageOptions={[10, 25, 50, 100]}
        component="div"
        count={OrderCount?.OrderCount || 0}
        rowsPerPage={rowsPerPage}
        page={page}
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}
      />
      <TableContainer sx={{ maxHeight: 600, maxWidth: 1000 }}>
        <Table stickyHeader size="small" aria-label="sticky table">
          <TableHead>
            <TableRow>
              <TableCell />
              <TableCell align="left">Номер заказа</TableCell>
              <TableCell align="center">Дата</TableCell>
              <TableCell align="center">Сумма</TableCell>
              <TableCell align="center">Количество товаров</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>

              {rows.map((row) => {
                return (
                  <Row row={row} key={row._id}></Row>
                );
              })}
          </TableBody>
        </Table>
      </TableContainer>
      <TablePagination
        rowsPerPageOptions={[10, 25, 100]}
        component="div"
        count={OrderCount?.OrderCount || 0}
        rowsPerPage={rowsPerPage}
        page={page}
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}
      />
    </Paper>
  );
}

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" align="left">
          {row._id}
        </TableCell>
        <TableCell align="center">{TimestampConv(row.createdAt)}</TableCell>
        <TableCell align="center">{row.total}</TableCell>
        <TableCell align='center'>{Array.isArray(row.orderGoods) ? row.orderGoods?.length : 0}</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) => {
                      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>
  );
}