import { EditFilled } from "@ant-design/icons";
import { Card, Space, Table } from "antd";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import { alphaSort } from "../../utils/sorters";
import LaborAllocationsAdjustmentEdit from "../labor-allocations-adjustment-edit/labor-allocations-adjustment-edit.component";
import "./labor-allocations-table.styles.scss";
import { CalculateAllocationsTotals } from "./labor-allocations-table.utility";
import _ from "lodash";
const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  technician: selectTechnician,
});

export function LaborAllocationsTable({
  jobId,
  joblines,
  timetickets,
  bodyshop,
  adjustments,
  technician,
}) {
  const { t } = useTranslation();
  const [totals, setTotals] = useState([]);
  const [state, setState] = useState({
    sortedInfo: {
      columnKey: "cost_center",
      field: "cost_center",
      order: "ascend",
    },
    filteredInfo: {},
  });

  useEffect(() => {
    if (!!joblines && !!timetickets && !!bodyshop);
    setTotals(
      CalculateAllocationsTotals(
        bodyshop.md_responsibility_centers,
        joblines,
        timetickets,
        adjustments
      )
    );
    if (!jobId) setTotals([]);
  }, [joblines, timetickets, bodyshop, adjustments, jobId]);

  const columns = [
    {
      title: t("timetickets.fields.cost_center"),
      dataIndex: "cost_center",
      key: "cost_center",
      defaultSortOrder: "cost_center",
      sorter: (a, b) => alphaSort(a.cost_center, b.cost_center),
      sortOrder:
        state.sortedInfo.columnKey === "cost_center" && state.sortedInfo.order,
      render: (text, record) => `${record.cost_center} (${record.mod_lbr_ty})`,
    },
    {
      title: t("jobs.labels.hrs_total"),
      dataIndex: "total",
      key: "total",
      sorter: (a, b) => a.total - b.total,
      sortOrder:
        state.sortedInfo.columnKey === "total" && state.sortedInfo.order,
      render: (text, record) => record.total.toFixed(1),
    },
    {
      title: t("jobs.labels.hrs_claimed"),
      dataIndex: "hrs_claimed",
      key: "hrs_claimed",
      sorter: (a, b) => a.claimed - b.claimed,
      sortOrder:
        state.sortedInfo.columnKey === "claimed" && state.sortedInfo.order,
      render: (text, record) => record.claimed && record.claimed.toFixed(1),
    },
    {
      title: t("jobs.labels.adjustments"),
      dataIndex: "adjustments",
      key: "adjustments",
      sorter: (a, b) => a.adjustments - b.adjustments,
      sortOrder:
        state.sortedInfo.columnKey === "adjustments" && state.sortedInfo.order,
      render: (text, record) => (
        <Space wrap>
          {record.adjustments.toFixed(1)}
          {!technician && (
            <LaborAllocationsAdjustmentEdit
              jobId={jobId}
              adjustments={adjustments}
              mod_lbr_ty={record.opcode}
              refetchQueryNames={["GET_LINE_TICKET_BY_PK"]}
            >
              <EditFilled />
            </LaborAllocationsAdjustmentEdit>
          )}
        </Space>
      ),
    },
    {
      title: t("jobs.labels.difference"),
      dataIndex: "difference",

      key: "difference",
      sorter: (a, b) => a.difference - b.difference,
      sortOrder:
        state.sortedInfo.columnKey === "difference" && state.sortedInfo.order,
      render: (text, record) => (
        <strong
          style={{
            color: record.difference >= 0 ? "green" : "red",
          }}
        >
          {_.round(record.difference, 1)}
        </strong>
      ),
    },
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
  };

  return (
    <Card title={t("jobs.labels.laborallocations")}>
      <Table
        columns={columns}
        rowKey="cost_center"
        pagination={false}
        onChange={handleTableChange}
        dataSource={totals}
        scroll={{
          x: true,
        }}
      />
    </Card>
  );
}
export default connect(mapStateToProps, null)(LaborAllocationsTable);
