import { Box, Typography } from "@mui/material";
import ResponsiveTable, { Column } from "common/ResponsiveTable";
import { cloneDeep } from "lodash";
//import { getTableIcons } from "common/ResponsiveTable";
//import MaterialTable, { Column, MTableToolbar } from "material-table";
import { Transaction } from "models/Transaction";
import moment from "moment";
import ObjectDescriber from "objects/ObjectDescriber";
import React, { useEffect, useState } from "react";
import TransactionDataDisplay from "./transactionDataDisplay";

interface Props {
  transactions: Transaction[];
  loading?: boolean;
  objectNames?: Map<string, string>;
}

export default function TransactionViewer(props: Props) {
  const { transactions, loading, objectNames } = props;
  const [displayedRows, setDisplayedRows] = useState<Transaction[]>([])
  const [tablePage, setTablePage] = useState(0)
  const [pageSize, setPageSize] = useState(10)

  useEffect(()=>{
    let clone: Transaction[] = cloneDeep(transactions)
    let rows = clone.splice(tablePage * pageSize, pageSize)
    setDisplayedRows(rows)
  },[transactions, tablePage, pageSize])

  const columns: Column<Transaction>[] = [
    {
      title: "Date",
      render: row => {
        return (
          <Box padding={2}>
            <Typography>{moment(row.transaction.timestamp).format("YYYY-MM-DD")}</Typography>
          </Box>
        );
      }
    },
    {
      title: "From",
      render: row => {
        return (
          <Box padding={2}>
            <Typography>{ObjectDescriber(row.transaction.fromObject).name}</Typography>
            <Typography>
              {objectNames ? objectNames.get(row.transaction.fromKey) : row.transaction.fromKey}
            </Typography>
          </Box>
        );
      }
    },
    {
      title: "To",
      render: row => {
        return (
          <Box padding={2}>
            <Typography>{ObjectDescriber(row.transaction.toObject).name}</Typography>
            <Typography>
              {objectNames ? objectNames.get(row.transaction.toKey) : row.transaction.toKey}
            </Typography>
          </Box>
        );
      }
    },
    {
      title: "Transaction",
      render: row => {
        return (
          <Box padding={2}> 
            <TransactionDataDisplay transaction={row} />
          </Box>
        );
      }
    }
  ];

  const handleChange = (event: any) => {
    setPageSize(event.target.value);
  };

  const myTable = () => {
    console.log(transactions)
    return (
      <ResponsiveTable<Transaction>
        isLoading={loading}
        title={"Inventory Transactions"}
        page={tablePage}
        columns={columns}
        pageSize={pageSize}
        rows={displayedRows}
        total={transactions.length}
        setPage={page => setTablePage(page)}
        handleRowsPerPageChange={handleChange}
      />
    )
  };

  return <Box>{myTable()}</Box>;
}
