import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import Box from "@mui/material/Box";
import Collapse from "@mui/material/Collapse";
import IconButton from "@mui/material/IconButton";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell, { tableCellClasses } from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Typography from "@mui/material/Typography";
import Paper from "@mui/material/Paper";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import { styled } from "@mui/material/styles";
import { getListProvidersByIdSupply } from "../services/orders";
import { grey } from "@mui/material/colors";

const StyledTableCell = styled(TableCell)(() => ({
  [`&.${tableCellClasses.head}`]: {
    backgroundColor: "#23282c",
    color: "#fff",
    fontSize: 16,
    height: "10px",
  },
  [`&.${tableCellClasses.body}`]: {
    fontSize: 14,
    color: "#fff",
    border: "unset",
    backgroundColor: "#23282c",
    paddingTop: "5px",
    paddingBottom: "5px",
  },
}));

const StyledTableRow = styled(TableRow)(() => ({
  "&:nth-of-type(odd)": {
    backgroundColor: "#23282c",
    height: "20px",
  },
  // hide last border
  "&:last-child td, &:last-child th": {
    border: 0,
  },
}));

function createData(
  name,
  price,
  lastOrderQuantity,
  lastOrderDate,
  description,
  orders,
  providersFull
) {
  /*  console.log("provFULL: ");
  console.log(
    "name:" + name,
    "price: " + price,
    "lastOrderQuantity: " + lastOrderQuantity,
    "lastOrderDate: " + lastOrderDate,
    "description: " + description,
    "orders: " + orders,
    "providersFull: " + providersFull
  );

  console.log("providersFull dsde ACa");
  console.log(providersFull); */

  if (orders) {
    const providerMaped = orders.map((order) => {
      console.log("provMap: " + order.amount);
      console.log("provMap- name: " + order.date);
      return {
        key: order.amount,
        dateH: order.date.slice(0, 10),
        priceH: order.amount,
        quantityH: order.quantity,
      };
    });

    return {
      name,
      price,
      lastOrderQuantity,
      lastOrderDate,
      description,
      history: providerMaped,
    };  
  } else {
    return {
      name,
      price,
      lastOrderQuantity,
      lastOrderDate,
      description,

      history: [],
    };
  }
}

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

  return (
    <React.Fragment>
      <StyledTableRow
        sx={{ "& > *": { borderBottom: "unset" }, background: "#23282C" }}
      >
        <StyledTableCell>
          <IconButton
            aria-label="expand row"
            size="small"
            onClick={() => setOpen(!open)}
          >
            {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
          </IconButton>
        </StyledTableCell>
        {/*     <StyledTableCell component="th" scope="row">{row._id}</StyledTableCell> */}
        <StyledTableCell style={{ display: "none" }} align="right">
          {row._id}
        </StyledTableCell>
        <StyledTableCell align="left">{row.name}</StyledTableCell>
        <StyledTableCell align="right">{row.price}</StyledTableCell>
        <StyledTableCell align="right">{row.lastOrderQuantity}</StyledTableCell>
        <StyledTableCell align="right">{row.lastOrderDate}</StyledTableCell>
      </StyledTableRow>
      <StyledTableRow>
        <StyledTableCell style={{ paddingTop: 0 }} colSpan={6}>
          <Collapse in={open} timeout="auto" unmountOnExit>
            <Box sx={{ marginTop: 1, borderBottom: "0.5px solid grey" }}>
              <h4
                style={{ paddingLeft: 15, color: "#3082aa", fontWeight: "100" }}
              >
                Historial
              </h4>

              <Table
                size="small"
                aria-label="historial"
                style={{ width: "100%" }}
              >
                <TableHead>
                  <StyledTableRow>
                    <StyledTableCell
                      style={{ fontSize: "13px" }}
                      align="right"
                    ></StyledTableCell>
                    <StyledTableCell style={{ fontSize: "13px" }} align="right">
                      Precio
                    </StyledTableCell>
                    <StyledTableCell style={{ fontSize: "13px" }} align="right">
                      Cantidad
                    </StyledTableCell>
                    <StyledTableCell style={{ fontSize: "13px" }} align="right">
                      Fecha de ingreso
                    </StyledTableCell>
                  </StyledTableRow>
                </TableHead>
                <TableBody>
                  {row.history.map((historyRow) => (
                    <StyledTableRow key={historyRow._id}>
                      <StyledTableCell
                        style={{ fontSize: "13px" }}
                        align="right"
                        width="29%"
                      ></StyledTableCell>
                      <StyledTableCell
                        style={{ fontSize: "13px" }}
                        align="right"
                      >
                        {historyRow.priceH}
                      </StyledTableCell>
                      <StyledTableCell
                        style={{ fontSize: "13px" }}
                        align="right"
                        width="17%"
                      >
                        {historyRow.quantityH}
                      </StyledTableCell>
                      <StyledTableCell
                        style={{ fontSize: "13px" }}
                        component="th"
                        scope="row"
                        align="right"
                      >
                        {historyRow.dateH}
                      </StyledTableCell>
                    </StyledTableRow>
                  ))}
                </TableBody>
              </Table>
            </Box>
          </Collapse>
        </StyledTableCell>
      </StyledTableRow>
    </React.Fragment>
  );
}

export default function DataTableProvidersDetail(props) {
  console.log("providers desde dataTableP");
  console.log(props.selectedSupply);

  const [orders, setOrders] = useState([]);

  let total = 0;

  const params = useParams();

  const loadOrders = async () => {
    const orders = await getListProvidersByIdSupply(params.id);
    setOrders(orders);
  };

  useEffect(() => {
    loadOrders();
  }, []);

  /*   console.log("ver los orders");
  console.log(orders); */

  const rows = orders.map((e) => {
    total += e.total;
    props.funcTotal(total);

    // last orders amount
    const lastOrder = e.orders[e.orders.length - 1].amount;

    //last orders quantity
    const lastOrderQuantity = e.orders[e.orders.length - 1].quantity;

    // last orders date
    const lastOrderDate = e.orders[e.orders.length - 1].date.slice(0, 10);

    return createData(
      e.name.name,
      lastOrder,
      lastOrderQuantity,
      lastOrderDate,
      e.name.description,
      e.orders,
      orders
    );
  });

  return (
    <>
      <TableContainer component={Paper} style={{ width: "93%" }}>
        <Table aria-label="collapsible table">
          <TableHead>
            <StyledTableRow>
              <StyledTableCell />
              <StyledTableCell>Proveedor</StyledTableCell>
              <StyledTableCell align="right">Precio</StyledTableCell>
              <StyledTableCell align="right">Cantidad</StyledTableCell>
              <StyledTableCell align="right">
                última Fecha de Ingreso
              </StyledTableCell>
            </StyledTableRow>
          </TableHead>
          <TableBody>
            {rows.map((row) => (
              <Row key={row._id} row={row} />
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </>
  );
}
