import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';

import { Table, TableBody, TableCell, TableContainer, TableRow, Typography } from '@/mui/components';

import styles from './Total.module.scss';

const renderTable = (props) => (
  <TableContainer elevation={0}>
    <Table aria-label="table-totals" size="small">
      <TableBody>
        {props.rows.map((row) => {
          const value = props.info?.[row.value]?.value ?? null;
          const valueMultiplied = row.needMultiply
            ? (props.info?.[row.value]?.value ?? 0) * 100
            : props.info?.[row.value]?.value;
          const valueFormatted = valueMultiplied?.toLocaleString(undefined, {
            minimumFractionDigits: row.prefix?.length || row.postfix?.length ? 2 : 0,
            maximumFractionDigits: 2,
          });

          const percent = props.info?.[row.value]?.change;
          const roundedPercent = percent ? Math.round(percent * 100) : 0;
          const percentFormatted = roundedPercent > 0 ? `+${roundedPercent}%` : `${roundedPercent}%`;

          return (
            <TableRow key={row.value}>
              <TableCell className={styles.Cell}>
                <Typography variant="caption" color="text.primary" fontWeight={400}>
                  {row.label}
                </Typography>
              </TableCell>
              {value !== null ? (
                <TableCell className={styles.Cell} align="right">
                  <Typography variant="caption" color="text.primary" fontWeight={400}>
                    {`${row.prefix ?? ''}${valueFormatted}${row.postfix ?? ''}`}
                  </Typography>
                </TableCell>
              ) : (
                <TableCell className={styles.Cell} align="right" />
              )}

              {!Number.isNaN(parseInt(percent, 10)) ? (
                <TableCell className={classNames(styles.Cell, styles.Cell___withPercent)}>
                  <Typography
                    className={styles.Percent}
                    variant="caption"
                    color={roundedPercent < 0 ? 'error.main' : 'success.main'}
                    fontWeight={400}
                  >
                    {percentFormatted ?? ''}
                  </Typography>
                </TableCell>
              ) : (
                <TableCell className={styles.Cell} />
              )}
            </TableRow>
          );
        })}
      </TableBody>
    </Table>
  </TableContainer>
);

function Total({ rowsInColumn = null, ...props }) {
  const chunkArray = (myArray, chunkSize) => {
    const arrayLength = myArray.length;
    const tempArray = [];

    for (let index = 0; index < arrayLength; index += chunkSize) {
      const myChunk = myArray.slice(index, index + chunkSize);
      tempArray.push(myChunk);
    }

    return tempArray;
  };

  const data = rowsInColumn ? chunkArray(props.rows, rowsInColumn) : [props.rows];

  return (
    <div className={styles.Total}>
      {data.map((item) => (
        <div
          key={item.id}
          className={classNames(styles.Total_item, {
            [styles.Total_item___withMargin]: !!rowsInColumn,
          })}
        >
          {renderTable({ rows: item, info: props.info })}
        </div>
      ))}
    </div>
  );
}

Total.propTypes = {
  info: PropTypes.shape({}).isRequired,
  rows: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  rowsInColumn: PropTypes.number,
};

export default Total;
