import { Card } from "antd";
import { 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 OwnerDetailUpdateJobsComponent from "../owner-detail-update-jobs/owner-detail-update-jobs.component";
import { selectIsPartsEntry } from "../../redux/application/application.selectors";
import getPartsBasePath from "../../utils/getPartsBasePath.js";
import ResponsiveTable from "../responsive-table/responsive-table.component";

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

function OwnerDetailJobsComponent({ bodyshop, owner, isPartsEntry }) {
  const { t } = useTranslation();
  const [selectedJobs, setSelectedJobs] = useState([]);
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" }
  });
  const basePath = getPartsBasePath(isPartsEntry);

  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={`${basePath}/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.vehicle"),
      dataIndex: "vehicleid",
      key: "vehicleid",
      sorter: (a, b) =>
        alphaSort(
          `${a.v_model_yr || ""} ${a.v_make_desc || ""} ${a.v_model_desc || ""}`,
          `${b.v_model_yr || ""} ${b.v_make_desc || ""} ${b.v_model_desc || ""}`
        ),
      sortOrder: state.sortedInfo.columnKey === "vehicleid" && state.sortedInfo.order,
      render: (text, record) =>
        record.vehicleid ? (
          <Link to={`${basePath}/vehicles/${record.vehicleid}`}>
            {`${record.v_model_yr || ""} ${record.v_make_desc || ""} ${record.v_model_desc || ""}`.trim()}
          </Link>
        ) : (
          t("jobs.errors.novehicle")
        )
    },
    {
      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("owners.labels.relatedjobs")}
      extra={
        <OwnerDetailUpdateJobsComponent
          selectedJobs={selectedJobs}
          owner={owner}
          disabled={selectedJobs.length === 0}
        />
      }
    >
      <ResponsiveTable
        pagination={{ placement: "bottom" }}
        columns={columns}
        mobileColumnKeys={["ro_number", "vehicleid", "status", "actual_completion"]}
        scroll={{ x: true }}
        rowKey="id"
        dataSource={owner.jobs}
        onChange={handleTableChange}
        rowSelection={{
          onSelect: (record, selected, selectedRows) => {
            setSelectedJobs(selectedRows ? selectedRows.map((i) => i.id) : []);
          },
          onSelectAll: (selected, selectedRows) => {
            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)(OwnerDetailJobsComponent);
