import React, { useState } from "react";
import { Table } from "antd";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import VehicleDetailUpdateJobsComponent from "../vehicle-detail-update-jobs/vehicle-detail-update-jobs.component";

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

export function VehicleDetailJobsComponent({ vehicle, bodyshop }) {
  const { t } = useTranslation();
  const [selectedJobs, setSelectedJobs] = useState([]);

  const columns = [
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "ro_number",
      key: "ro_number",
      ellipsis: true,
      render: (text, record) => (
        <Link to={`/manage/jobs/${record.id}`}>
          {record.ro_number ? record.ro_number : `EST ${record.est_number}`}
        </Link>
      )
    },
    {
      title: t("jobs.fields.owner"),
      dataIndex: "owner",
      key: "owner",
      render: (text, record) => (
        <Link to={`/manage/owners/${record.owner.id}`}>
          {`${record.ownr_fn} ${record.ownr_ln}`}
        </Link>
      )
    },
    {
      title: t("jobs.fields.clm_no"),
      dataIndex: "clm_no",
      key: "clm_no"
    },
    {
      title: t("jobs.fields.status"),
      dataIndex: "status",
      key: "status"
    },

    {
      title: t("jobs.fields.clm_total"),
      dataIndex: "clm_total",
      key: "clm_total",
      render: (text, record) => (
        <CurrencyFormatter>{record.clm_total}</CurrencyFormatter>
      )
    }
  ];

  return (
    <Table
      title={() => (
        <div>
          <VehicleDetailUpdateJobsComponent
            selectedJobs={selectedJobs}
            vehicle={vehicle}
            disabled={selectedJobs.length === 0}
          />
        </div>
      )}
      pagination={{ position: "bottom" }}
      columns={columns.map(item => ({ ...item }))}
      rowKey="id"
      dataSource={vehicle.jobs}
      rowSelection={{
        onSelect: (record, selected, selectedRows) => {
          setSelectedJobs(selectedRows ? selectedRows.map(i => i.id) : []);
        },

        selectedRowKeys: selectedJobs,
        getCheckboxProps: record => ({
          disabled: bodyshop.md_ro_statuses.open_statuses
            ? !bodyshop.md_ro_statuses.open_statuses.includes(record.status)
            : true
        })
      }}
    />
  );
}

export default connect(mapStateToProps, null)(VehicleDetailJobsComponent);
