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

export default function JobTotalsTableParts({ job }) {
  const { t } = useTranslation();
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: {}
  });

  const insuranceAdjustments = useMemo(() => {
    if (!job.job_totals) return [];
    if (!job.job_totals?.parts?.adjustments) return [];
    const adjs = [];
    Object.keys(job.job_totals?.parts?.adjustments).forEach((key) => {
      if (Dinero(job.job_totals?.parts?.adjustments[key]).getAmount() !== 0) {
        adjs.push({
          id: key,
          amount: Dinero(job.job_totals.parts.adjustments[key])
        });
      }
    });

    return adjs;
  }, [job.job_totals]);

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

  const columns = [
    {
      title: t("joblines.fields.part_type"),
      dataIndex: "id",
      key: "id",
      sorter: (a, b) => alphaSort(t(`jobs.fields.${a.id.toLowerCase()}`), t(`jobs.fields.${b.id.toLowerCase()}`)),
      width: "80%",
      sortOrder: state.sortedInfo.columnKey === "id" && state.sortedInfo.order,
      render: (text, record) => t(`jobs.fields.${record.id.toLowerCase()}`)
    },
    {
      title: t("joblines.fields.total"),
      dataIndex: "total",
      key: "total",
      sorter: (a, b) => a.total.amount - b.total.amount,
      sortOrder: state.sortedInfo.columnKey === "total" && state.sortedInfo.order,
      width: "20%",
      align: "right",
      render: (text, record) => Dinero(record.total).toFormat()
    }
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
  };
  return (
    <ResponsiveTable
      columns={columns}
      mobileColumnKeys={["total", "id"]}
      rowKey="id"
      pagination={false}
      onChange={handleTableChange}
      dataSource={data}
      scroll={{
        x: true
      }}
      summary={() => (
        <>
          <ResponsiveTable.Summary.Row>
            <ResponsiveTable.Summary.Cell>{t("jobs.labels.prt_dsmk_total")}</ResponsiveTable.Summary.Cell>
            <ResponsiveTable.Summary.Cell align="right">
              {Dinero(job.job_totals.parts.parts.prt_dsmk_total).toFormat()}
            </ResponsiveTable.Summary.Cell>
          </ResponsiveTable.Summary.Row>

          <ResponsiveTable.Summary.Row>
            <ResponsiveTable.Summary.Cell>
              <strong>{t("jobs.labels.partstotal")}</strong>
            </ResponsiveTable.Summary.Cell>

            <ResponsiveTable.Summary.Cell align="right">
              <strong>{Dinero(job.job_totals.parts.parts.total).toFormat()}</strong>
            </ResponsiveTable.Summary.Cell>
          </ResponsiveTable.Summary.Row>
          {
            //TODO:AIO This shoudl only be in the US version. need to verify whether this causes problems for the CA version.
            insuranceAdjustments.length > 0 && (
              <ResponsiveTable.Summary.Row>
                <ResponsiveTable.Summary.Cell colSpan={24}>
                  {t("jobs.labels.profileadjustments")}
                </ResponsiveTable.Summary.Cell>
              </ResponsiveTable.Summary.Row>
            )
          }
          {insuranceAdjustments.map((adj, idx) => (
            <ResponsiveTable.Summary.Row key={idx}>
              <ResponsiveTable.Summary.Cell>{t(`jobs.fields.${adj.id.toLowerCase()}`)}</ResponsiveTable.Summary.Cell>

              <ResponsiveTable.Summary.Cell align="right">{adj.amount.toFormat()}</ResponsiveTable.Summary.Cell>
            </ResponsiveTable.Summary.Row>
          ))}
        </>
      )}
    />
  );
}
