import React, { useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import JobsCloseLaborMaterialAllocation from "../../components/jobs-close-labmat-allocation/jobs-close-labmat-allocation.component";
import { selectBodyshop } from "../../redux/user/user.selectors";
import JobsClosePartsAllocation from "../../components/jobs-close-parts-allocation/jobs-close-parts-allocation.component";
import Dinero from "dinero.js";
import JobsCloseTotals from "../../components/jobs-close-totals/jobs-close-totals.component";
import JobsCloseAutoAllocate from "../../components/jobs-close-auto-allocate/jobs-close-auto-allocate.component";
import JobsCloseSaveButton from "../../components/jobs-close-save-button/jobs-close-save-button.component";
import JobsCloseExportButton from "../../components/jobs-close-export-button/jobs-close-export-button.component";
import JobsScoreboardAdd from "../../components/job-scoreboard-add-button/job-scoreboard-add-button.component";

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

export function JobsCloseComponent({ job, bodyshop, jobTotals }) {
  const [invoiced, setInvoiced] = useState(!!job.invoice_allocation);
  const [labmatAllocations, setLabmatAllocations] = useState(
    !!job.invoice_allocation && !!job.invoice_allocation.labMatAllocations
      ? Object.keys(job.invoice_allocation.labMatAllocations).reduce(
          (acc, val) => {
            if (val.includes("subtotal")) {
              acc[val] = Dinero(job.invoice_allocation.labMatAllocations[val]);
            } else {
              acc[val] = {
                ...job.invoice_allocation.labMatAllocations[val],
                total: Dinero(
                  job.invoice_allocation.labMatAllocations[val].total
                ),
                allocations: job.invoice_allocation.labMatAllocations[
                  val
                ].allocations.map((item) => {
                  return { ...item, amount: Dinero(item.amount) };
                }),
              };
            }

            return acc;
          },
          {}
        )
      : Object.keys(jobTotals.rates).reduce((acc, val) => {
          acc[val] = jobTotals.rates[val];
          if (val.includes("subtotal")) return acc;
          //Not a subtotal - therefore can be allocated.
          acc[val].allocations = [];
          return acc;
        }, {})
  );

  const [partsAllocations, setPartsAllocations] = useState(
    !!job.invoice_allocation && !!job.invoice_allocation.partsAllocations
      ? Object.keys(job.invoice_allocation.partsAllocations).reduce(
          (acc, val) => {
            acc[val] = {
              ...job.invoice_allocation.partsAllocations[val],
              total: Dinero(job.invoice_allocation.partsAllocations[val].total),
              allocations: job.invoice_allocation.partsAllocations[
                val
              ].allocations.map((item) => {
                return { ...item, amount: Dinero(item.amount) };
              }),
            };
            return acc;
          },
          {}
        )
      : {
          ...Object.keys(jobTotals.parts.parts.list).reduce((acc, val) => {
            acc[val] = { ...jobTotals.parts.parts.list[val], allocations: [] };

            return acc;
          }, {}),
          pas: {
            ...jobTotals.parts.sublets,
            allocations: [],
          },
        }
  );

  const labmatAllocatedTotalsArray = Object.keys(labmatAllocations)
    .filter((i) => !i.includes("subtotal"))
    .map((i) => labmatAllocations[i].allocations)
    .flat();

  const labmatAllocatedTotal = Dinero({
    amount: labmatAllocatedTotalsArray.reduce((acc, val) => {
      return (acc = acc + val.amount.getAmount());
    }, 0),
  });

  const partsAllocatedTotalsArray = Object.keys(partsAllocations)
    .map((i) => partsAllocations[i].allocations)
    .flat();

  const partsAllocatedTotal = Dinero({
    amount: partsAllocatedTotalsArray.reduce((acc, val) => {
      return (acc = acc + val.amount.getAmount());
    }, 0),
  });

  return (
    <div>
      <JobsCloseSaveButton
        jobId={job.id}
        invoiced={invoiced}
        setInvoicedState={setInvoiced}
        partsAllocations={partsAllocations}
        labMatAllocations={labmatAllocations}
        jobTotals={jobTotals}
        disabled={!!job.date_exported}
        suspenseAmount={jobTotals.totals.subtotal
          .subtract(labmatAllocatedTotal)
          .subtract(partsAllocatedTotal)
          .getAmount()}
      />
      <JobsScoreboardAdd job={job} disabled={!invoiced} />
      <JobsCloseExportButton jobId={job.id} disabled={!invoiced} />
      <JobsCloseTotals
        jobTotals={jobTotals}
        labMatTotal={labmatAllocatedTotal}
        partsTotal={partsAllocatedTotal}
      />
      <JobsCloseAutoAllocate
        labmatAllocations={labmatAllocations}
        setLabmatAllocations={setLabmatAllocations}
        partsAllocations={partsAllocations}
        setPartsAllocations={setPartsAllocations}
        disabled={!!job.date_exported}
      />
      <JobsCloseLaborMaterialAllocation
        labmatAllocations={labmatAllocations}
        setLabmatAllocations={setLabmatAllocations}
        labMatTotalAllocation={labmatAllocatedTotal}
        invoiced={!!job.date_exported}
      />
      <JobsClosePartsAllocation
        partsAllocations={partsAllocations}
        setPartsAllocations={setPartsAllocations}
        partsAllocatedTotal={partsAllocatedTotal}
        invoiced={!!job.date_exported}
      />
    </div>
  );
}
export default connect(mapStateToProps, null)(JobsCloseComponent);
