import { Alert, Card, Col, Row, Space, Statistic, Tooltip, Typography } from "antd";
import Dinero from "dinero.js";
import { useTranslation } from "react-i18next";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import AlertComponent from "../alert/alert.component";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component";
import "./job-bills-total.styles.scss";
import BlurWrapperComponent from "../feature-wrapper/blur-wrapper.component";
import UpsellComponent, { upsellEnum } from "../upsell/upsell.component";
import { HasFeatureAccess } from "../feature-wrapper/feature-wrapper.component";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({});

export function JobBillsTotalComponent({
  bodyshop,
  loading,
  bills,
  partsOrders,
  jobTotals,
  showWarning,
  warningCallback
}) {
  const { t } = useTranslation();

  if (loading) return <LoadingSkeleton />;
  if (!jobTotals) {
    if (showWarning && warningCallback && typeof warningCallback === "function") {
      warningCallback({ key: "bills", warning: t("jobs.errors.nofinancial") });
    }
    return <AlertComponent type="error" title={t("jobs.errors.nofinancial")} />;
  }

  const totals = jobTotals;

  let billTotals = Dinero();
  let billCms = Dinero();
  let lbrAdjustments = Dinero();
  let totalReturns = Dinero();
  let totalReturnsMarkedNotReceived = Dinero();
  let totalReturnsMarkedReceived = Dinero();

  partsOrders.forEach((p) =>
    p.parts_order_lines.forEach((pol) => {
      if (p.return) {
        totalReturns = totalReturns.add(
          Dinero({
            amount: Math.round((pol.act_price || 0) * 100)
          }).multiply(pol.quantity)
        );

        if (pol.cm_received === null) {
          //TODO:AIO This was previously removed. Check if functionality impacted.
          // Skip this calculation for bills posted prior to the CNR change.
          return;
        } else {
          if (pol.cm_received === false) {
            totalReturnsMarkedNotReceived = totalReturnsMarkedNotReceived.add(
              Dinero({
                amount: Math.round((pol.act_price || 0) * 100)
              }).multiply(pol.quantity)
            );
          } else {
            totalReturnsMarkedReceived = totalReturnsMarkedReceived.add(
              Dinero({
                amount: Math.round((pol.act_price || 0) * 100)
              }).multiply(pol.quantity)
            );
          }
        }
      }
    })
  );

  bills.forEach((i) =>
    i.billlines.forEach((il) => {
      if (!i.is_credit_memo) {
        billTotals = billTotals.add(
          Dinero({
            amount: Math.round((il.actual_price || 0) * 100)
          }).multiply(il.quantity)
        );
      } else {
        billCms = billCms.add(
          Dinero({
            amount: Math.round((il.actual_price || 0) * 100)
          }).multiply(il.quantity)
        );
      }
      if (il.deductedfromlbr) {
        lbrAdjustments = lbrAdjustments.add(
          Dinero({
            amount: Math.round((il.actual_price || 0) * 100)
          }).multiply(il.quantity)
        );
      }
    })
  );

  const totalPartsSublet = Dinero(totals.parts.parts.total)
    .add(Dinero(totals.parts.sublets.total))
    .add(Dinero(totals.additional.shipping))
    .add(Dinero(totals.additional.towing))
    .add(
      InstanceRenderManager({
        imex: Dinero(),
        rome: Dinero(totals.additional.additionalCosts)
      })
    ); // Additional costs were captured for Rome, but not imex.

  const discrepancy = totalPartsSublet.subtract(billTotals);

  const discrepWithLbrAdj = discrepancy.add(lbrAdjustments);

  const discrepWithCms = discrepWithLbrAdj.add(totalReturns);
  const calculatedCreditsNotReceived = totalReturns.subtract(billCms); //billCms is tracked as a negative number.

  if (showWarning && warningCallback && typeof warningCallback === "function") {
    if (discrepWithCms.getAmount() !== 0) {
      warningCallback({
        key: "bills",
        warning: t("jobs.labels.outstanding_reconciliation_discrep")
      });
    }
    if (calculatedCreditsNotReceived.getAmount() > 0) {
      warningCallback({ key: "cm", warning: t("jobs.labels.outstanding_credit_memos") });
    }
  }
  const hasBillsAccess = HasFeatureAccess({ bodyshop, featureName: "bills" });
  return (
    <Row gutter={[16, 16]}>
      <Col {...(hasBillsAccess ? { md: 24, lg: 18 } : { span: 12 })}>
        <Card title={t("jobs.labels.jobtotals")} style={{ height: "100%" }}>
          <Space wrap size="large">
            <Tooltip
              title={
                <div
                  dangerouslySetInnerHTML={{
                    __html: t("jobs.labels.plitooltips.partstotal")
                  }}
                />
              }
            >
              <Statistic title={t("jobs.labels.rosaletotal")} value={totalPartsSublet.toFormat()} />
            </Tooltip>
            <Typography.Title>-</Typography.Title>
            <Tooltip
              title={
                <div
                  dangerouslySetInnerHTML={{
                    __html: t("jobs.labels.plitooltips.billtotal")
                  }}
                />
              }
            >
              <BlurWrapperComponent featureName="bills" overrideValueFunction="RandomDinero">
                <Statistic title={t("bills.labels.retailtotal")} value={billTotals.toFormat()} />
              </BlurWrapperComponent>
            </Tooltip>
            <Typography.Title>=</Typography.Title>
            <Tooltip
              title={
                <div
                  dangerouslySetInnerHTML={{
                    __html: t("jobs.labels.plitooltips.discrep1")
                  }}
                />
              }
            >
              <BlurWrapperComponent featureName="bills" overrideValueFunction="RandomDinero">
                <Statistic
                  title={t("bills.labels.discrepancy")}
                  styles={{
                    content: {
                      color: discrepancy.getAmount() === 0 ? "green" : "red"
                    }
                  }}
                  value={discrepancy.toFormat()}
                />
              </BlurWrapperComponent>
            </Tooltip>
            <Typography.Title>+</Typography.Title>
            <Tooltip
              title={
                <div
                  dangerouslySetInnerHTML={{
                    __html: t("jobs.labels.plitooltips.laboradj")
                  }}
                />
              }
            >
              <BlurWrapperComponent featureName="bills" overrideValueFunction="RandomDinero">
                <Statistic title={t("bills.labels.dedfromlbr")} value={lbrAdjustments.toFormat()} />
              </BlurWrapperComponent>
            </Tooltip>
            <Typography.Title>=</Typography.Title>
            <Tooltip
              title={
                <div
                  dangerouslySetInnerHTML={{
                    __html: t("jobs.labels.plitooltips.discrep2")
                  }}
                />
              }
            >
              <BlurWrapperComponent featureName="bills" overrideValueFunction="RandomDinero">
                <Statistic
                  title={t("bills.labels.discrepancy")}
                  styles={{
                    content: {
                      color: discrepWithLbrAdj.getAmount() === 0 ? "green" : "red"
                    }
                  }}
                  value={discrepWithLbrAdj.toFormat()}
                />
              </BlurWrapperComponent>
            </Tooltip>
            <Typography.Title>+</Typography.Title>
            <Tooltip
              title={
                <div
                  dangerouslySetInnerHTML={{
                    __html: t("jobs.labels.plitooltips.creditmemos")
                  }}
                />
              }
            >
              <BlurWrapperComponent featureName="bills" overrideValueFunction="RandomDinero">
                <Statistic title={t("bills.labels.totalreturns")} value={totalReturns.toFormat()} />
              </BlurWrapperComponent>
            </Tooltip>
            <Typography.Title>=</Typography.Title>
            <Tooltip
              title={
                <div
                  dangerouslySetInnerHTML={{
                    __html: t("jobs.labels.plitooltips.discrep3")
                  }}
                />
              }
            >
              <BlurWrapperComponent featureName="bills" overrideValueFunction="RandomDinero">
                <Statistic
                  title={t("bills.labels.discrepancy")}
                  styles={{
                    content: {
                      color: discrepWithCms.getAmount() === 0 ? "green" : "red"
                    }
                  }}
                  value={discrepWithCms.toFormat()}
                />
              </BlurWrapperComponent>
            </Tooltip>
          </Space>
          {showWarning &&
            (discrepWithCms.getAmount() !== 0 ||
              discrepWithLbrAdj.getAmount() !== 0 ||
              discrepancy.getAmount() !== 0) && (
              <Alert
                style={{ margin: "8px 0px" }}
                type="warning"
                title={t("jobs.labels.outstanding_reconciliation_discrep")}
              />
            )}
        </Card>
      </Col>
      <Col md={24} lg={6}>
        <Card title={t("jobs.labels.returntotals")} style={{ height: "100%" }}>
          <Space wrap>
            <Tooltip
              title={
                <div
                  dangerouslySetInnerHTML={{
                    __html: t("jobs.labels.plitooltips.totalreturns")
                  }}
                />
              }
            >
              <BlurWrapperComponent featureName="bills" overrideValueFunction="RandomDinero">
                <Statistic title={t("bills.labels.totalreturns")} value={totalReturns.toFormat()} />
              </BlurWrapperComponent>
            </Tooltip>
            <Tooltip
              title={
                <div
                  dangerouslySetInnerHTML={{
                    __html: t("jobs.labels.plitooltips.calculatedcreditsnotreceived")
                  }}
                />
              }
            >
              <BlurWrapperComponent featureName="bills" overrideValueFunction="RandomDinero">
                <Statistic
                  title={t("bills.labels.calculatedcreditsnotreceived")}
                  styles={{
                    content: {
                      color: calculatedCreditsNotReceived.getAmount() <= 0 ? "green" : "red"
                    }
                  }}
                  value={
                    calculatedCreditsNotReceived.getAmount() >= 0
                      ? calculatedCreditsNotReceived.toFormat()
                      : Dinero().toFormat()
                  }
                />
              </BlurWrapperComponent>
            </Tooltip>
            <Tooltip
              title={
                <div
                  dangerouslySetInnerHTML={{
                    __html: t("jobs.labels.plitooltips.creditsnotreceived")
                  }}
                />
              }
            >
              <BlurWrapperComponent featureName="bills" overrideValueFunction="RandomDinero">
                <Statistic
                  title={t("bills.labels.creditsnotreceived")}
                  styles={{
                    content: {
                      color: totalReturnsMarkedNotReceived.getAmount() <= 0 ? "green" : "red"
                    }
                  }}
                  value={
                    totalReturnsMarkedNotReceived.getAmount() >= 0
                      ? totalReturnsMarkedNotReceived.toFormat()
                      : Dinero().toFormat()
                  }
                />
              </BlurWrapperComponent>
            </Tooltip>
          </Space>
          {showWarning && calculatedCreditsNotReceived.getAmount() > 0 && (
            <Alert style={{ margin: "8px 0px" }} type="warning" title={t("jobs.labels.outstanding_credit_memos")} />
          )}
        </Card>
      </Col>
      {!hasBillsAccess && (
        <Col span={6}>
          <Card style={{ height: "100%" }}>
            <UpsellComponent upsell={upsellEnum().bills.autoreconcile} disableMask />
          </Card>
        </Col>
      )}
    </Row>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(JobBillsTotalComponent);
