import { SyncOutlined } from "@ant-design/icons";
import { Button, Card, Input, Space, Table } from "antd";
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 PhoneFormatter from "../../utils/PhoneFormatter";
import { alphaSort } from "../../utils/sorters";
import StartChatButton from "../chat-open-button/chat-open-button.component";
import _ from "lodash";

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",
      width: "8%",
      sorter: (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: "owner",
      key: "owner",
      ellipsis: true,
      // sorter: (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),
      width: "25%",
      // sortOrder: sortcolumn === "owner" && sortorder,
      render: (text, record) => {
        return record.owner ? (
          <Link to={"/manage/owners/" + record.owner.id}>
            {`${record.ownr_fn || ""} ${record.ownr_ln || ""} ${
              record.ownr_co_nm || ""
            }`}
          </Link>
        ) : (
          <span>{`${record.ownr_fn || ""} ${record.ownr_ln || ""} ${
            record.ownr_co_nm || ""
          }`}</span>
        );
      },
    },
    {
      title: t("jobs.fields.ownr_ph1"),
      dataIndex: "ownr_ph1",
      key: "ownr_ph1",
      width: "12%",
      ellipsis: true,
      render: (text, record) => {
        return record.ownr_ph1 ? (
          <span>
            <PhoneFormatter>{record.ownr_ph1}</PhoneFormatter>
            <StartChatButton phone={record.ownr_ph1} jobid={record.id} />
          </span>
        ) : null;
      },
    },
    {
      title: t("jobs.fields.status"),
      dataIndex: "status",
      key: "status",
      width: "10%",
      ellipsis: true,
      sorter: (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",
      width: "15%",
      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",
      width: "8%",
      ellipsis: true,
      sorter: (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",
      width: "12%",
      ellipsis: true,
      sorter: (a, b) => alphaSort(a.clm_no, b.clm_no),
      sortOrder: sortcolumn === "clm_no" && sortorder,
      render: (text, record) => {
        return record.clm_no ? (
          <span>{record.clm_no}</span>
        ) : (
          t("general.labels.unknown")
        );
      },
    },
    {
      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",
      width: "10%",
      sorter: (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",
      width: "8%",
      render: (text, record) => (
        <CurrencyFormatter>{record.owner_owing}</CurrencyFormatter>
      ),
    },
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    console.log("filters :>> ", filters);
    search.page = pagination.current;
    search.sortcolumn = sorter.columnKey;
    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>
          <Button onClick={() => refetch()}>
            <SyncOutlined />
          </Button>
          <Input.Search
            placeholder={t("general.labels.search")}
            onSearch={(value) => {
              search.search = value;
              history.push({ search: queryString.stringify(search) });
            }}
            enterButton
          />
        </Space>
      }
    >
      <Table
        loading={loading}
        scroll={{ x: true }}
        pagination={{
          position: "top",
          pageSize: 25,
          current: parseInt(page || 1),
          total: total,
        }}
        columns={columns}
        rowKey="id"
        dataSource={jobs}
        onChange={handleTableChange}
      />
    </Card>
  );
}
export default connect(mapStateToProps, mapDispatchToProps)(JobsList);
