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, Button, Collapse, IconButton, Link, Typography } from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import { useSelector } from 'react-redux';
import { useGetGoodCountQuery, useGetGoodFindQuery } from '../../store/categoriesApi';
import { Link as RouterLink } from "react-router-dom"






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 AdminGoodsTable() {
  const userId = useSelector(state => state.auth.user?.sub.id)
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const {data: GoodCount} = useGetGoodCountQuery({})
  const count = GoodCount?.GoodCount || 1
  const goods = useGetGoodFindQuery({limit: rowsPerPage, skip: page * rowsPerPage, sort: {_id: -1}})
  const rows = goods?.data ? Object.values(goods.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={GoodCount?.GoodCount || 1}
        rowsPerPage={rowsPerPage}
        page={page}
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}
      />
      <TableContainer sx={{ maxWidth: 1200 }}>
        <Table stickyHeader size="small" aria-label="sticky table">
          <TableHead>
            <TableRow>
              <TableCell />
              <TableCell align="left">ID</TableCell>
              <TableCell align="left" sortDirection='asc'>Дата создания</TableCell>
              <TableCell align="left">Название</TableCell>              
              <TableCell align="left">Цена, грн.</TableCell>
              <TableCell align="left">Категория</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>

              {rows.map((row) => {
                return (
                  <Row row={row} key={row._id}></Row>
                );
              })}
          </TableBody>
        </Table>
      </TableContainer>
      <TablePagination
        rowsPerPageOptions={[10, 25, 50, 100]}
        component="div"
        count={count || 1}
        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="left">{(row.name)}</TableCell>
        <TableCell align="left">{row.price}</TableCell>
        {/* <TableCell align='center'>{}</TableCell> */}
        <TableCell align='left'>{Array.isArray(row.categories) ? row.categories[0]?.name : 0}</TableCell>
      </TableRow>
      <TableRow>
        <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}>
          <Collapse in={open} timeout="auto" unmountOnExit>
            <Box sx={{ margin: 1 }}>
              <Link to={`/admin/good/${row._id}`} underline="none" variant="button" sx={{ color: "ButtonText" }} component={RouterLink}>
                <Button variant='outlined'>Редактировать</Button>
              </Link>
            </Box>
          </Collapse>
        </TableCell>
      </TableRow>
    </React.Fragment>
  );
}