import { useEffect } from "react";

import { Alert, Card } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { t } from "i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { alphaSort } from "../../utils/sorters";

const mapStateToProps = createStructuredSelector({});

const mapDispatchToProps = () => ({});

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

export function JobCloseRGuardSublet({ job, warningCallback }) {
  const subletsNotDone = job?.joblines.filter(
    (j) => (j.part_type === "PAS" || j.part_type === "PASL") && (!j.sublet_completed || !j.sublet_ignored)
  );

  const columns = [
    {
      title: t("joblines.fields.line_desc"),
      dataIndex: "line_desc",
      fixed: "left",
      key: "line_desc",
      sorter: (a, b) => alphaSort(a.line_desc, b.line_desc),
      onCell: (record) => ({
        className: record.manual_line && "job-line-manual",
        style: {
          ...(record.critical ? { boxShadow: " -.5em 0 0 #FFC107" } : {})
        }
      }),
      ellipsis: true
    },
    {
      title: t("joblines.fields.act_price"),
      dataIndex: "act_price",
      key: "act_price",
      sorter: (a, b) => a.act_price - b.act_price,

      ellipsis: true,
      render: (text, record) => <CurrencyFormatter>{record.act_price}</CurrencyFormatter>
    },
    {
      title: t("joblines.fields.part_qty"),
      dataIndex: "part_qty",
      key: "part_qty"
    },
    {
      title: t("joblines.fields.notes"),
      dataIndex: "notes",
      key: "notes"
    }
  ];

  useEffect(() => {
    if (subletsNotDone.length > 0) {
      warningCallback({ key: "sublet", warning: t("jobs.labels.outstanding_sublets") });
    }
  }, [subletsNotDone.length, warningCallback]);

  return (
    <Card title={t("jobs.labels.subletsnotcompleted")}>
      <ResponsiveTable
        dataSource={subletsNotDone}
        columns={columns}
        mobileColumnKeys={["line_desc", "act_price", "part_qty", "notes"]}
        pagination={false}
        rowKey="id"
        bordered
        size="small"
      />
      {subletsNotDone.length > 0 && (
        <Alert style={{ margin: "8px 0px" }} type="warning" title={t("jobs.labels.outstanding_sublets")} />
      )}
    </Card>
  );
}
