import React, { useState } from "react";
import PropTypes from "prop-types";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { Grid } from "../grid/Grid";

const BoxShowTable = ({
  columns,
  data,
  isDashboard,
  allColors,
  customColors,
}) => {
  const [expandedRows, setExpandedRows] = useState([]);

  const getColumnColor = (column) => {
    if (allColors) {
      return allColors.color;
    } else {
      const c = customColors?.find((item) => item.name === column?.name)
        ? customColors?.find((item) => item.name === column?.name)
        : customColors?.find((item) => item.rest === true);
      if (c) {
        return c.color;
      } else {
        if (isDashboard) {
          return "#f4c3c3";
        } else if (customColors?.length) {
          return "#f6e58d";
        } else {
          return null;
        }
      }
    }
  };

  const handleExpandClick = (rowIndex) => {
    setExpandedRows((prev) =>
      prev.includes(rowIndex)
        ? prev.filter((index) => index !== rowIndex)
        : [...prev, rowIndex]
    );
  };

  function isPositiveNumber(str) {
    const data = String(str);
    const sanitizedStr = data?.replace(/,/g, "");
    const num = Number(sanitizedStr);

    if (!isNaN(num)) {
      return num >= 0;
    } else {
      return true;
    }
  }

  const getTextColor = (column) => {
    if (allColors?.text) return allColors.text;
    const bgColor = getColumnColor(column);

    if (!bgColor) return "white";
    if (
      bgColor === "black" ||
      bgColor === "blue" ||
      bgColor === "red" ||
      bgColor === "brown" ||
      bgColor === "green"
    ) {
      return "white";
    }
    return "black";
  };

  return (
    <Grid xs={12} container justifyContent="center" style={{ width: "100%" }}>
      <Grid
        container
        xs={12}
        spacing={1}
        justifyContent="space-between"
        style={{ width: "100%" }}
      >
        {data?.map((row, rowIndex) => {
          let visibleCellIndex = 0;
          const isExpanded = expandedRows.includes(rowIndex);

          return (
            <Grid key={rowIndex} xs={data.length === 1 ? 12 : 6}>
              <Box
                display="flex"
                flexDirection="column"
                border={1}
                borderRadius={3}
                style={{ width: "100%", borderColor: "darkgray" }}
              >
                {row
                  .slice(
                    0,
                    8 +
                      columns.filter((item) => item?.visible === false)?.length
                  )
                  .map(
                    (cell, cellIndex) =>
                      columns[cellIndex]?.visible && (
                        <Grid
                          borderRadius={
                            cellIndex === 0 ? "11px 11px 0px 0px" : 0
                          }
                          key={cellIndex}
                          alignItems="center"
                          justifyContent="space-between"
                          display="flex"
                          xs={12}
                          sx={{
                            backgroundColor:
                              visibleCellIndex++ % 2 === 0
                                ? isDashboard
                                  ? "white"
                                  : "#daeef0"
                                : "white",

                            borderStyle: "solid",
                            borderWidth: "1px",
                            borderColor: "darkgray",
                            padding: 0,
                          }}
                        >
                          <Grid
                            item
                            xs={5}
                            sx={{
                              backgroundColor:
                                getColumnColor(columns[cellIndex]) ||
                                (isDashboard ? "#c23616" : "#547687"),
                              borderRadius: "4px 0 0 4px",
                              paddingY: "8px",
                            }}
                          >
                            <Typography
                              sx={{
                                fontSize:
                                  columns[cellIndex]?.name?.length <= 15
                                    ? 13
                                    : 10,
                                color: getTextColor(columns[cellIndex]),
                              }}
                            >{`${columns[cellIndex]?.name}`}</Typography>
                          </Grid>

                          <Grid
                            item
                            xs={7}
                            style={{
                              fontSize: 12,
                              width: "100%",
                              color: !isPositiveNumber(cell) ? "red" : "black",
                              lineBreak: "anywhere",
                            }}
                          >
                            {!isPositiveNumber(cell)
                              ? String(cell).replace("-", "") + "-‌ ‌"
                              : cell}
                          </Grid>
                        </Grid>
                      )
                  )}
                {isExpanded &&
                  row.slice(8)?.map(
                    (cell, cellIndex) =>
                      columns[cellIndex + 8]?.visible && (
                        <Grid
                          key={cellIndex + 8}
                          alignItems="center"
                          justifyContent="space-between"
                          display="flex"
                          xs={12}
                          sx={{
                            backgroundColor:
                              visibleCellIndex++ % 2 === 0
                                ? isDashboard
                                  ? "white"
                                  : "#daeef0"
                                : "white",
                            borderStyle: "solid",
                            borderWidth: "1px",
                            borderColor: "darkgray",
                            padding: 0,
                          }}
                        >
                          <Grid
                            item
                            xs={5}
                            sx={{
                              backgroundColor:
                                getColumnColor(columns[cellIndex + 8]) ||
                                (isDashboard ? "#c23616" : "#547687"),
                              borderRadius: "4px 0 0 4px",
                              paddingY: "8px",
                            }}
                          >
                            <Typography
                              sx={{
                                fontSize:
                                  columns[cellIndex + 8]?.name?.length <= 15
                                    ? 13
                                    : 10,
                                color: getTextColor(columns[cellIndex + 8]),
                              }}
                            >{`${columns[cellIndex + 8]?.name}`}</Typography>
                          </Grid>

                          <Grid
                            item
                            xs={7}
                            style={{
                              fontSize: 12,
                              width: "100%",
                              color: !isPositiveNumber(cell) ? "red" : "black",
                              lineBreak: "anywhere",
                            }}
                          >
                            {!isPositiveNumber(cell)
                              ? String(cell).replace("-", "") + "-‌ ‌"
                              : cell}
                          </Grid>
                        </Grid>
                      )
                  )}
                {row.length > 8 && (
                  <IconButton onClick={() => handleExpandClick(rowIndex)}>
                    <ExpandMoreIcon
                      sx={{
                        transform: isExpanded
                          ? "rotate(180deg)"
                          : "rotate(0deg)",
                        transition: "transform 0.3s",
                      }}
                    />
                  </IconButton>
                )}
              </Box>
            </Grid>
          );
        })}
      </Grid>
    </Grid>
  );
};

BoxShowTable.propTypes = {
  columns: PropTypes.any,
  data: PropTypes.any,
  ignore: PropTypes.array,
};

export default BoxShowTable;
