import { Button, Space, Statistic } from "antd";
import Dinero from "dinero.js";
import _ from "lodash";
import React, { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  reconcileByAssocLine,
  reconcileByPrice,
} from "./job-reconciliation-totals.utility";

export default function JobReconciliationTotals({
  billLines,
  jobLines,
  jobLineState,
  billLineState,
}) {
  const [errors, setErrors] = useState([]);
  const { t } = useTranslation();
  const selectedBillLines = billLineState[0];
  const selectedJobLines = jobLineState[0];

  const totals = useMemo(() => {
    const jlLookup = _.keyBy(selectedJobLines, (i) => i);
    const billLookup = _.keyBy(selectedBillLines, (i) => i);

    return {
      joblinesTotal: jobLines
        .filter((jl) => !!jlLookup[jl.id])
        .reduce((acc, val) => {
          return acc.add(
            Dinero({ amount: Math.round((val.act_price || 0) * 100) }).multiply(
              val.part_qty || 1
            )
          );
        }, Dinero()),
      billLinesTotal: billLines
        .filter((bl) => !!billLookup[bl.id])
        .reduce((acc, val) => {
          return acc.add(
            Dinero({
              amount: Math.round((val.actual_price || 0) * 100),
            })
              .multiply(val.quantity || 1)
              .multiply(val.bill.is_credit_memo ? -1 : 1)
          );
        }, Dinero()),
    };
  }, [billLines, jobLines, selectedBillLines, selectedJobLines]);

  return (
    <div style={{ display: "inline-block" }}>
      <div>
        <Space>
          <Statistic
            title={t("jobs.labels.reconciliation.joblinestotal")}
            value={totals.joblinesTotal.toFormat()}
          />
          <Statistic
            title={t("jobs.labels.reconciliation.billlinestotal")}
            value={totals.billLinesTotal.toFormat()}
          />
          <Statistic
            title={t("jobs.labels.reconciliation.discrepancy")}
            value={totals.joblinesTotal
              .subtract(totals.billLinesTotal)
              .toFormat()}
          />
        </Space>
      </div>
      <div>
        <Space direction="horizontal">
          <Button
            onClick={() =>
              reconcileByAssocLine(
                jobLines,
                jobLineState,
                billLines,
                billLineState,
                setErrors
              )
            }
          >
            {t("jobs.labels.reconciliation.byassoc")}
          </Button>
          <Button
            onClick={() =>
              reconcileByPrice(
                jobLines,
                jobLineState,
                billLines,
                billLineState,
                setErrors
              )
            }
          >
            {t("jobs.labels.reconciliation.byprice")}
          </Button>
          <Button
            onClick={() => {
              jobLineState[1]([]);
              billLineState[1]([]);
              setErrors([]);
            }}
          >
            {t("jobs.labels.reconciliation.clear")}
          </Button>
        </Space>
      </div>
      {errors.length > 0 && (
        <div>
          {t("general.labels.errors")}
          <ul>
            {errors.map((error, idx) => (
              <li key={idx}>{error}</li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}
