import { Box, Card, Typography } from "@mui/material";
import { Contract } from "models/Contract";
import { Transaction } from "models/Transaction";
import BarGraph, { BarData } from "charts/BarGraph";
import { useEffect, useState } from "react";
import moment, { Moment } from "moment";
import { getGrainUnit } from "utils";
import { pond } from "protobuf-ts/pond";

interface Props {
  contract: Contract;
  transactions: Transaction[];
}

export default function ContractTransactionGraph(props: Props) {
  const { contract, transactions } = props;
  const [data, setData] = useState<BarData[]>([]);

  useEffect(() => {
    let d: BarData[] = [];
    transactions.forEach(t => {
      let time: Moment = moment(t.transaction.timestamp);
      let value = 0;
      //this seems confusing but the transaction model contains the transaction as defined in the pond and then need to get the specific transaction data
      //which is defined in the pond as a oneof for different types of transactions ie: grainTransaction
      let transaction = t.transaction.transaction;
      if (transaction?.grainTransaction) {
        value = transaction.grainTransaction.bushels;
        if (
          getGrainUnit() === pond.GrainUnit.GRAIN_UNIT_WEIGHT &&
          transaction.grainTransaction.bushelsPerTonne > 1
        ) {
          value = value / transaction.grainTransaction.bushelsPerTonne;
        }
      }
      d.push({
        timestamp: time.valueOf(),
        value: value
      });
    });
    setData(d);
  }, [transactions]);

  const daysRemaining = () => {
    let days = "Delivery Window Closed";
    const endDate = contract.settings.deliveryWindow?.endDate;

    if (endDate && moment(endDate).isAfter(moment.now())) {
      days = "To be completed " + moment(endDate).fromNow();
    }
    return days;
  };

  return (
    <Card style={{ height: "100%", padding: 10 }}>
      <Box height={"10%"}>
        <Typography style={{ fontWeight: 650, fontSize: 20 }}>
          Deliveries ({daysRemaining()})
        </Typography>
      </Box>
      <BarGraph
        data={data}
        barColour={contract.colour}
        useGradient
        yMin={0}
        customHeight={"90%"}
        labels
        labelSize={20}
        labelColour="white"
      />
    </Card>
  );
}
