import { useQuery } from "@apollo/client/react";
import { Statistic } from "antd";
import Dinero from "dinero.js";
import { useTranslation } from "react-i18next";
import { QUERY_JOB_PAYMENT_TOTALS } from "../../graphql/payments.queries";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";

export default function PaymentFormTotalPayments({ jobid }) {
  const { t } = useTranslation();

  const { loading, error, data } = useQuery(QUERY_JOB_PAYMENT_TOTALS, {
    variables: { id: jobid },
    skip: !jobid,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent title={error.message} type="error" />;

  if (!data) return <></>;
  const totalPayments = data.jobs_by_pk.payments.reduce((acc, val) => {
    return acc.add(Dinero({ amount: Math.round((val?.amount || 0) * 100) }));
  }, Dinero());

  const balance =
    data.jobs_by_pk.job_totals && Dinero(data.jobs_by_pk.job_totals.totals.total_repairs).subtract(totalPayments);

  return (
    <div style={{ display: "flex", justifyContent: "space-evenly" }}>
      <Statistic title={t("payments.labels.totalpayments")} value={totalPayments.toFormat()} />
      {balance && (
        <Statistic
          title={t("payments.labels.balance")}
          styles={{ content: { color: balance.getAmount() !== 0 ? "red" : "green" } }}
          value={(balance && balance.toFormat()) || ""}
        />
      )}
      {!balance && <div>{t("jobs.errors.nofinancial")}</div>}
    </div>
  );
}
