import { Card, Table } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import { alphaSort, dateSort, statusSort } from "../../utils/sorters";
import OwnerNameDisplay, {
  OwnerNameDisplayFunction,
} from "../owner-name-display/owner-name-display.component";
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 [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" },
  });

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

  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 || t("general.labels.na")}
        </Link>
      ),
      sorter: (a, b) => alphaSort(a.ro_number, b.ro_number),
      sortOrder:
        state.sortedInfo.columnKey === "ro_number" && state.sortedInfo.order,
    },
    {
      title: t("jobs.fields.owner"),
      dataIndex: "owner",
      key: "owner",
      sorter: (a, b) =>
        alphaSort(OwnerNameDisplayFunction(a), OwnerNameDisplayFunction(b)),
      sortOrder:
        state.sortedInfo.columnKey === "owner" && state.sortedInfo.order,
      render: (text, record) => (
        <Link to={`/manage/owners/${record.owner.id}`}>
          <OwnerNameDisplay ownerObject={record} />
        </Link>
      ),
    },
    {
      title: t("jobs.fields.clm_no"),
      dataIndex: "clm_no",
      key: "clm_no",
      sorter: (a, b) => alphaSort(a.clm_no, b.clm_no),
      sortOrder:
        state.sortedInfo.columnKey === "clm_no" && state.sortedInfo.order,
    },
    {
      title: t("jobs.fields.status"),
      dataIndex: "status",
      key: "status",
      sorter: (a, b) =>
        statusSort(a.status, b.status, bodyshop.md_ro_statuses.statuses),
      sortOrder:
        state.sortedInfo.columnKey === "status" && state.sortedInfo.order,
      filters: bodyshop.md_ro_statuses.statuses.map((status) => ({
        text: status,
        value: status,
      })),
      onFilter: (value, record) => value.includes(record.status),
    },
    {
      title: t("jobs.fields.actual_completion"),
      dataIndex: "actual_completion",
      key: "actual_completion",
      render: (text, record) => (
        <DateTimeFormatter>{record.actual_completion}</DateTimeFormatter>
      ),
      sorter: (a, b) => dateSort(a.actual_completion, b.actual_completion),
      sortOrder:
        state.sortedInfo.columnKey === "actual_completion" &&
        state.sortedInfo.order,
    },
    {
      title: t("jobs.fields.clm_total"),
      dataIndex: "clm_total",
      key: "clm_total",
      render: (text, record) => (
        <CurrencyFormatter>{record.clm_total}</CurrencyFormatter>
      ),
      sorter: (a, b) => a.clm_total - b.clm_total,
      sortOrder:
        state.sortedInfo.columnKey === "clm_total" && state.sortedInfo.order,
    },
  ];

  return (
    <Card
      title={t("vehicles.labels.relatedjobs")}
      extra={
        <VehicleDetailUpdateJobsComponent
          selectedJobs={selectedJobs}
          vehicle={vehicle}
          disabled={selectedJobs.length === 0}
        />
      }
    >
      <Table
        columns={columns}
        rowKey="id"
        scroll={{ x: true }}
        dataSource={vehicle.jobs}
        onChange={handleTableChange}
        rowSelection={{
          onSelect: (record, selected, selectedRows) => {
            setSelectedJobs(selectedRows ? selectedRows.map((i) => i.id) : []);
          },
          onSelectAll: (selected, selectedRows, changeRows) => {
            setSelectedJobs(
              selectedRows
                ? selectedRows
                    .filter((i) =>
                      bodyshop.md_ro_statuses.active_statuses.includes(i.status)
                    )
                    .map((i) => i.id)
                : []
            );
          },
          selectedRowKeys: selectedJobs,
          getCheckboxProps: (record) => ({
            disabled: bodyshop.md_ro_statuses.active_statuses
              ? !bodyshop.md_ro_statuses.active_statuses.includes(record.status)
              : true,
          }),
        }}
      />
    </Card>
  );
}

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