import { Space } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import Dinero from "dinero.js";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import { alphaSort } from "../../utils/sorters";

export default function JobTotalsTableLabor({ job }) {
  const { t } = useTranslation();
  const [state, setState] = useState({
    sortedInfo: {
      columnKey: "profitcenter_labor",
      field: "profitcenter_labor",
      order: "ascend"
    },
    filteredInfo: {}
  });

  const data = useMemo(() => {
    return Object.keys(job.job_totals.rates)
      .filter((key) => key !== "mapa" && key !== "mash" && key !== "subtotal" && key !== "rates_subtotal")
      .map((key) => {
        return {
          id: key,
          ...job.job_totals.rates[key]
        };
      });
  }, [job.job_totals.rates]);

  const columns = [
    {
      title: t("joblines.fields.profitcenter_labor"),
      dataIndex: "profitcenter_labor",
      key: "profitcenter_labor",
      defaultSortOrder: "ascend",
      sorter: (a, b) =>
        alphaSort(t(`jobs.fields.rate_${a.id.toLowerCase()}`), t(`jobs.fields.rate_${b.id.toLowerCase()}`)),
      sortOrder: state.sortedInfo.columnKey === "profitcenter_labor" && state.sortedInfo.order,
      render: (text, record) => t(`jobs.fields.rate_${record.id.toLowerCase()}`)
    },
    {
      title: t("jobs.labels.rates"),
      dataIndex: "rate",
      key: "rate",
      align: "right",
      sorter: (a, b) => a.rate - b.rate,
      sortOrder: state.sortedInfo.columnKey === "rate" && state.sortedInfo.order,
      render: (text, record) => <CurrencyFormatter>{record.rate}</CurrencyFormatter>
    },
    {
      title: t("joblines.fields.mod_lb_hrs"),
      dataIndex: "mod_lb_hrs",
      key: "mod_lb_hrs",
      sorter: (a, b) => a.hours - b.hours,
      sortOrder: state.sortedInfo.columnKey === "mod_lb_hrs" && state.sortedInfo.order,
      render: (text, record) => record.hours.toFixed(1)
    },
    ...InstanceRenderManager({
      imex: [
        {
          title: t("joblines.fields.total"),
          dataIndex: "total",
          key: "total",
          align: "right",
          sorter: (a, b) => a.total.amount - b.total.amount,
          sortOrder: state.sortedInfo.columnKey === "total" && state.sortedInfo.order,
          render: (text, record) => Dinero(record.total).toFormat()
        }
      ],
      rome: [
        {
          title: t("joblines.fields.amount"),
          dataIndex: "base",
          key: "base",
          align: "right",
          sorter: (a, b) => a.base.amount - b.base.amount,
          sortOrder: state.sortedInfo.columnKey === "base" && state.sortedInfo.order,
          render: (text, record) => Dinero(record.base).toFormat()
        },
        {
          title: t("joblines.fields.adjustment"),
          dataIndex: "adjustment",
          key: "adjustment",
          align: "right",
          sorter: (a, b) => a.adjustment.amount - b.adjustment.amount,
          sortOrder: state.sortedInfo.columnKey === "adjustment" && state.sortedInfo.order,
          render: (text, record) => Dinero(record.adjustment).toFormat()
        },
        {
          title: t("joblines.fields.total"),
          dataIndex: "total",
          key: "total",
          align: "right",
          sorter: (a, b) => a.total.amount - b.total.amount,
          sortOrder: state.sortedInfo.columnKey === "total" && state.sortedInfo.order,
          render: (text, record) => Dinero(record.total).toFormat()
        }
      ]
    })
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
  };
  return (
    <ResponsiveTable
      columns={columns}
      mobileColumnKeys={["total", "profitcenter_labor", "rate", "mod_lb_hrs"]}
      rowKey="id"
      pagination={false}
      onChange={handleTableChange}
      dataSource={data}
      scroll={{
        x: true
      }}
      summary={() => (
        <>
          <ResponsiveTable.Summary.Row>
            <ResponsiveTable.Summary.Cell>
              <strong>{t("jobs.labels.labor_rates_subtotal")}</strong>
            </ResponsiveTable.Summary.Cell>
            <ResponsiveTable.Summary.Cell />
            <ResponsiveTable.Summary.Cell>
              {(job.job_totals.rates.mapa.hours + job.job_totals.rates.mash.hours).toFixed(1)}
            </ResponsiveTable.Summary.Cell>
            {InstanceRenderManager({
              imex: null,
              rome: (
                <>
                  <ResponsiveTable.Summary.Cell />
                  <ResponsiveTable.Summary.Cell />
                </>
              )
            })}
            <ResponsiveTable.Summary.Cell align="right">
              <strong>{Dinero(job.job_totals.rates.rates_subtotal).toFormat()}</strong>
            </ResponsiveTable.Summary.Cell>
          </ResponsiveTable.Summary.Row>
          <ResponsiveTable.Summary.Row>
            <ResponsiveTable.Summary.Cell>
              <Space>
                {t("jobs.labels.mapa")}
                {InstanceRenderManager({
                  imex:
                    (job.materials?.mapa ?? job.materials?.MAPA)?.cal_maxdlr > 0 &&
                    t("jobs.labels.threshhold", { amount: (job.materials.mapa ?? job.materials.MAPA).cal_maxdlr }),
                  rome:
                    job.materials?.MAPA?.cal_maxdlr !== undefined &&
                    t("jobs.labels.threshhold", { amount: job.materials.MAPA.cal_maxdlr })
                })}
              </Space>
            </ResponsiveTable.Summary.Cell>
            <ResponsiveTable.Summary.Cell align="right">
              <CurrencyFormatter>{job.job_totals.rates.mapa.rate}</CurrencyFormatter>
            </ResponsiveTable.Summary.Cell>
            <ResponsiveTable.Summary.Cell>{job.job_totals.rates.mapa.hours.toFixed(1)}</ResponsiveTable.Summary.Cell>
            {InstanceRenderManager({
              imex: (
                <ResponsiveTable.Summary.Cell align="right">
                  {Dinero(job.job_totals.rates.mapa.total).toFormat()}
                </ResponsiveTable.Summary.Cell>
              ),
              rome: (
                <>
                  <ResponsiveTable.Summary.Cell align="right">
                    {Dinero(job.job_totals.rates.mapa.base).toFormat()}
                  </ResponsiveTable.Summary.Cell>
                  <ResponsiveTable.Summary.Cell align="right">
                    {Dinero(job.job_totals.rates.mapa.adjustment).toFormat()}
                  </ResponsiveTable.Summary.Cell>
                  <ResponsiveTable.Summary.Cell align="right">
                    {Dinero(job.job_totals.rates.mapa.total).toFormat()}
                  </ResponsiveTable.Summary.Cell>
                </>
              )
            })}
          </ResponsiveTable.Summary.Row>
          <ResponsiveTable.Summary.Row>
            <ResponsiveTable.Summary.Cell>
              <Space wrap>
                {t("jobs.labels.mash")}
                {InstanceRenderManager({
                  imex:
                    (job.materials?.mash ?? job.materials?.MASH)?.cal_maxdlr > 0 &&
                    t("jobs.labels.threshhold", { amount: (job.materials.mash ?? job.materials.MASH).cal_maxdlr }),
                  rome:
                    job.materials?.MASH?.cal_maxdlr !== undefined &&
                    t("jobs.labels.threshhold", { amount: job.materials.MASH.cal_maxdlr })
                })}
              </Space>
            </ResponsiveTable.Summary.Cell>
            <ResponsiveTable.Summary.Cell align="right">
              <CurrencyFormatter>{job.job_totals.rates.mash.rate}</CurrencyFormatter>
            </ResponsiveTable.Summary.Cell>
            <ResponsiveTable.Summary.Cell>{job.job_totals.rates.mash.hours.toFixed(1)}</ResponsiveTable.Summary.Cell>
            {InstanceRenderManager({
              imex: (
                <ResponsiveTable.Summary.Cell align="right">
                  {Dinero(job.job_totals.rates.mash.total).toFormat()}
                </ResponsiveTable.Summary.Cell>
              ),
              rome: (
                <>
                  <ResponsiveTable.Summary.Cell align="right">
                    {Dinero(job.job_totals.rates.mash.base).toFormat()}
                  </ResponsiveTable.Summary.Cell>
                  <ResponsiveTable.Summary.Cell align="right">
                    {Dinero(job.job_totals.rates.mash.adjustment).toFormat()}
                  </ResponsiveTable.Summary.Cell>
                  <ResponsiveTable.Summary.Cell align="right">
                    {Dinero(job.job_totals.rates.mash.total).toFormat()}
                  </ResponsiveTable.Summary.Cell>
                </>
              )
            })}
          </ResponsiveTable.Summary.Row>
          <ResponsiveTable.Summary.Row>
            <ResponsiveTable.Summary.Cell>
              <strong>{t("jobs.labels.rates_subtotal")}</strong>
            </ResponsiveTable.Summary.Cell>
            <ResponsiveTable.Summary.Cell />
            <ResponsiveTable.Summary.Cell />
            {InstanceRenderManager({
              imex: null,
              rome: (
                <>
                  <ResponsiveTable.Summary.Cell />
                  <ResponsiveTable.Summary.Cell />
                </>
              )
            })}
            <ResponsiveTable.Summary.Cell align="right">
              <strong>{Dinero(job.job_totals.rates.subtotal).toFormat()}</strong>
            </ResponsiveTable.Summary.Cell>
          </ResponsiveTable.Summary.Row>
        </>
      )}
    />
  );
}
