import { Card } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { 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 CurrencyFormatter from "../../utils/CurrencyFormatter";
import { onlyUnique } from "../../utils/arrayHelper";
import { alphaSort } from "../../utils/sorters";

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

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

export function PartsQueueJobLinesComponent({ loading, jobLines }) {
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: {}
  });
  const { t } = useTranslation();

  const columns = [
    {
      title: "#",
      dataIndex: "line_no",
      key: "line_no",
      sorter: (a, b) => a.line_no - b.line_no,
      sortOrder: state.sortedInfo.columnKey === "line_no" && state.sortedInfo.order
    },
    {
      title: t("joblines.fields.line_desc"),
      dataIndex: "line_desc",
      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" } : {})
        }
      }),
      sortOrder: state.sortedInfo.columnKey === "line_desc" && state.sortedInfo.order,
      ellipsis: true
    },
    {
      title: t("joblines.fields.oem_partno"),
      dataIndex: "oem_partno",
      key: "oem_partno",
      sorter: (a, b) => alphaSort(a.oem_partno, b.oem_partno),
      sortOrder: state.sortedInfo.columnKey === "oem_partno" && state.sortedInfo.order,
      ellipsis: true,
      render: (text, record) => `${record.oem_partno || ""} ${record.alt_partno ? `(${record.alt_partno})` : ""}`.trim()
    },
    {
      title: t("joblines.fields.part_type"),
      dataIndex: "part_type",
      key: "part_type",
      filteredValue: state.filteredInfo.part_type || null,
      sorter: (a, b) => alphaSort(a.part_type, b.part_type),
      sortOrder: state.sortedInfo.columnKey === "part_type" && state.sortedInfo.order,
      filters: [
        {
          text: t("jobs.labels.partsfilter"),
          value: ["PAN", "PAC", "PAR", "PAL", "PAA", "PAM", "PAP", "PAS", "PASL", "PAG"]
        },
        {
          text: t("joblines.fields.part_types.PAN"),
          value: ["PAN"]
        },
        {
          text: t("joblines.fields.part_types.PAP"),
          value: ["PAP"]
        },
        {
          text: t("joblines.fields.part_types.PAL"),
          value: ["PAL"]
        },
        {
          text: t("joblines.fields.part_types.PAA"),
          value: ["PAA"]
        },
        {
          text: t("joblines.fields.part_types.PAG"),
          value: ["PAG"]
        },
        {
          text: t("joblines.fields.part_types.PAS"),
          value: ["PAS"]
        },
        {
          text: t("joblines.fields.part_types.PASL"),
          value: ["PASL"]
        },
        {
          text: t("joblines.fields.part_types.PAC"),
          value: ["PAC"]
        },
        {
          text: t("joblines.fields.part_types.PAR"),
          value: ["PAR"]
        },
        {
          text: t("joblines.fields.part_types.PAM"),
          value: ["PAM"]
        }
      ],
      onFilter: (value, record) => value.includes(record.part_type),
      render: (text, record) => (record.part_type ? t(`joblines.fields.part_types.${record.part_type}`) : null)
    },
    {
      title: t("joblines.fields.part_qty"),
      dataIndex: "part_qty",
      key: "part_qty"
    },
    {
      title: t("joblines.fields.act_price"),
      dataIndex: "act_price",
      key: "act_price",
      sorter: (a, b) => a.act_price - b.act_price,
      sortOrder: state.sortedInfo.columnKey === "act_price" && state.sortedInfo.order,
      ellipsis: true,
      render: (text, record) => (
        <CurrencyFormatter>
          {record.db_ref === "900510" || record.db_ref === "900511" ? record.prt_dsmk_m : record.act_price}
        </CurrencyFormatter>
      )
    },
    {
      title: t("joblines.fields.location"),
      dataIndex: "location",
      key: "location"
    },
    {
      title: t("joblines.fields.status"),
      dataIndex: "status",
      key: "status",
      sorter: (a, b) => alphaSort(a.status, b.status),
      sortOrder: state.sortedInfo.columnKey === "status" && state.sortedInfo.order,
      filteredValue: state.filteredInfo.status || null,
      filters:
        (jobLines &&
          jobLines
            .map((l) => l.status)
            .filter(onlyUnique)
            .map((s) => {
              return {
                text: s || t("dashboard.errors.status"),
                value: [s]
              };
            })) ||
        [],
      onFilter: (value, record) => value.includes(record.status)
    }
  ];

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

  return (
    <Card title={t("jobs.labels.parts_lines")}>
      <ResponsiveTable
        columns={columns}
        mobileColumnKeys={["status", "line_desc", "line_no", "oem_partno"]}
        rowKey="id"
        loading={loading}
        pagination={false}
        dataSource={jobLines}
        onChange={handleTableChange}
      />
    </Card>
  );
}

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