import { useEffect, useMemo } from "react";
import { Alert, Card } from "antd";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import Dinero from "dinero.js";
import DataLabel from "../data-label/data-label.component";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobCloseRoGuardProfit);

export function JobCloseRoGuardProfit({ job, warningCallback }) {
  const { t } = useTranslation();

  const total = useMemo(() => {
    return (
      job.payments &&
      job.payments.reduce((acc, val) => {
        acc = acc.add(Dinero({ amount: Math.round(val.amount * 100) }));
        return acc;
      }, Dinero())
    );
  }, [job.payments]);

  const balance = useMemo(() => {
    if (job?.job_totals && job.job_totals.totals.total_repairs)
      return Dinero(job.job_totals.totals.total_repairs).subtract(total);
    return Dinero({ amount: 0 }).subtract(total);
  }, [job, total]);

  useEffect(() => {
    if (balance.getAmount() !== 0) {
      warningCallback({ key: "ar", warning: t("jobs.labels.outstanding_ar") });
    }
  }, [balance, t, warningCallback]);

  return (
    <Card title={t("jobs.labels.accountsreceivable")} style={{ height: "100%" }}>
      <DataLabel label={t("payments.labels.totalpayments")}>{total.toFormat()}</DataLabel>
      <DataLabel
        styles={{ value: { color: balance.getAmount() !== 0 ? "red" : "green" } }}
        label={t("payments.labels.balance")}
      >
        {balance.toFormat()}
      </DataLabel>
      {balance.getAmount() !== 0 && (
        <Alert style={{ margin: "8px 0px" }} type="warning" title={t("jobs.labels.outstanding_ar")} />
      )}
    </Card>
  );
}
