import { SyncOutlined } from "@ant-design/icons";
import { Button, Card, Input, Space, Table, Typography } from "antd";
import _ from "lodash";
import queryString from "query-string";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link, useHistory, useLocation } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import StartChatButton from "../chat-open-button/chat-open-button.component";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";
const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});

export function JobsList({ bodyshop, refetch, loading, jobs, total }) {
  const search = queryString.parse(useLocation().search);
  const { page, sortcolumn, sortorder } = search;
  const history = useHistory();

  const { t } = useTranslation();
  const columns = [
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "ro_number",
      key: "ro_number",

      sorter: true, //(a, b) => alphaSort(a.ro_number, b.ro_number),
      sortOrder: sortcolumn === "ro_number" && sortorder,

      render: (text, record) => (
        <Link to={"/manage/jobs/" + record.id}>
          {record.ro_number || t("general.labels.na")}
        </Link>
      ),
    },

    {
      title: t("jobs.fields.owner"),
      dataIndex: "ownr_ln",
      key: "ownr_ln",
      ellipsis: true,
      //sorter: true, // (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),

      //sortOrder: sortcolumn === "ownr_ln" && sortorder,
      render: (text, record) => {
        return record.ownerid ? (
          <Link to={"/manage/owners/" + record.ownerid}>
            <OwnerNameDisplay ownerObject={record} />
          </Link>
        ) : (
          <span>
            <OwnerNameDisplay ownerObject={record} />
          </span>
        );
      },
    },
    {
      title: t("jobs.fields.ownr_ph1"),
      dataIndex: "ownr_ph1",
      key: "ownr_ph1",

      ellipsis: true,
      render: (text, record) => (
        <StartChatButton phone={record.ownr_ph1} jobid={record.id} />
      ),
    },
    {
      title: t("jobs.fields.ownr_ph2"),
      dataIndex: "ownr_ph2",
      key: "ownr_ph2",

      ellipsis: true,
      render: (text, record) => (
        <StartChatButton phone={record.ownr_ph2} jobid={record.id} />
      ),
    },
    {
      title: t("jobs.fields.status"),
      dataIndex: "status",
      key: "status",

      ellipsis: true,
      sorter: true, // (a, b) => alphaSort(a.status, b.status),
      sortOrder: sortcolumn === "status" && sortorder,
      render: (text, record) => {
        return record.status || t("general.labels.na");
      },
      filters: bodyshop.md_ro_statuses.statuses.map((s) => {
        return { text: s, value: [s] };
      }),
      onFilter: (value, record) => value.includes(record.status),
    },

    {
      title: t("jobs.fields.vehicle"),
      dataIndex: "vehicle",
      key: "vehicle",

      ellipsis: true,
      render: (text, record) => {
        return record.vehicleid ? (
          <Link to={"/manage/vehicles/" + record.vehicleid}>
            {`${record.v_model_yr || ""} ${record.v_make_desc || ""} ${
              record.v_model_desc || ""
            }`}
          </Link>
        ) : (
          <span>{`${record.v_model_yr || ""} ${record.v_make_desc || ""} ${
            record.v_model_desc || ""
          }`}</span>
        );
      },
    },
    {
      title: t("vehicles.fields.plate_no"),
      dataIndex: "plate_no",
      key: "plate_no",

      ellipsis: true,
      sorter: true, //(a, b) => alphaSort(a.plate_no, b.plate_no),
      sortOrder: sortcolumn === "plate_no" && sortorder,
      render: (text, record) => {
        return record.plate_no ? record.plate_no : "";
      },
    },
    {
      title: t("jobs.fields.clm_no"),
      dataIndex: "clm_no",
      key: "clm_no",

      ellipsis: true,
      sorter: true, //(a, b) => alphaSort(a.clm_no, b.clm_no),
      sortOrder: sortcolumn === "clm_no" && sortorder,
      render: (text, record) =>
        `${record.clm_no || ""}${
          record.po_number ? ` (PO: ${record.po_number})` : ""
        }`,
    },
    {
      title: t("jobs.fields.ins_co_nm"),
      dataIndex: "ins_co_nm",
      key: "ins_co_nm",
      ellipsis: true,
    },
    {
      title: t("jobs.fields.clm_total"),
      dataIndex: "clm_total",
      key: "clm_total",

      sorter: true, //(a, b) => a.clm_total - b.clm_total,
      sortOrder: sortcolumn === "clm_total" && sortorder,
      render: (text, record) => {
        return record.clm_total ? (
          <CurrencyFormatter>{record.clm_total}</CurrencyFormatter>
        ) : (
          t("general.labels.unknown")
        );
      },
    },
    {
      title: t("jobs.fields.owner_owing"),
      dataIndex: "owner_owing",
      key: "owner_owing",

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

  const handleTableChange = (pagination, filters, sorter) => {
    search.page = pagination.current;
    search.sortcolumn = sorter.column && sorter.column.key;
    search.sortorder = sorter.order;
    if (filters.status) {
      search.statusFilters = JSON.stringify(_.flattenDeep(filters.status));
    } else {
      delete search.statusFilters;
    }
    history.push({ search: queryString.stringify(search) });
  };

  return (
    <Card
      extra={
        <Space wrap>
          {search.search && (
            <>
              <Typography.Title level={4}>
                {t("general.labels.searchresults", { search: search.search })}
              </Typography.Title>
              <Button
                onClick={() => {
                  delete search.search;
                  history.push({ search: queryString.stringify(search) });
                }}
              >
                {t("general.actions.clear")}
              </Button>
            </>
          )}
          <Button onClick={() => refetch()}>
            <SyncOutlined />
          </Button>
          <Input.Search
            placeholder={search.search || t("general.labels.search")}
            onSearch={(value) => {
              search.search = value;
              history.push({ search: queryString.stringify(search) });
            }}
            enterButton
          />
        </Space>
      }
    >
      <Table
        loading={loading}
        pagination={{
          position: "top",
          pageSize: 25,
          current: parseInt(page || 1),
          total: total,
          showSizeChanger: false,
        }}
        columns={columns}
        rowKey="id"
        dataSource={jobs}
        onChange={handleTableChange}
      />
    </Card>
  );
}
export default connect(mapStateToProps, mapDispatchToProps)(JobsList);
