import { Button, Input, Table } from "antd";
import { SyncOutlined } from "@ant-design/icons";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, withRouter } from "react-router-dom";
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";

export default withRouter(function JobsList({
  searchTextState,
  refetch,
  loading,
  jobs,
  selectedJob,
  setSelectedJob,
  history
}) {
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" }
  });

  const { t } = useTranslation();

  const setSearchText = searchTextState[1];
  const columns = [
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "ro_number",
      key: "ro_number",
      width: "8%",
      // onFilter: (value, record) => record.ro_number.includes(value),
      // filteredValue: state.filteredInfo.text || null,
      sorter: (a, b) =>
        alphaSort(
          a.ro_number ? a.ro_number : "EST-" + a.est_number,
          b.ro_number ? b.ro_number : "EST-" + b.est_number
        ),
      sortOrder:
        state.sortedInfo.columnKey === "ro_number" && state.sortedInfo.order,

      render: (text, record) => (
        <span>
          <Link to={"/manage/jobs/" + record.id}>
            {record.ro_number ? record.ro_number : "EST-" + record.est_number}
          </Link>
        </span>
      )
    },
    {
      title: t("jobs.fields.owner"),
      dataIndex: "owner",
      key: "owner",
      ellipsis: true,
      sorter: (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),
      width: "25%",
      sortOrder:
        state.sortedInfo.columnKey === "owner" && state.sortedInfo.order,
      render: (text, record) => {
        return record.owner ? (
          <Link to={"/manage/owners/" + record.owner.id}>
            {record.ownr_fn} {record.ownr_ln}
          </Link>
        ) : (
          // t("jobs.errors.noowner")
          <span>{`${record.ownr_fn} ${record.ownr_ln}`}</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} />
          </span>
        ) : (
          t("general.labels.unknown")
        );
      }
    },
    {
      title: t("jobs.fields.status"),
      dataIndex: "status",
      key: "status",
      width: "10%",
      ellipsis: true,
      sorter: (a, b) => alphaSort(a.status, b.status),
      sortOrder:
        state.sortedInfo.columnKey === "status" && state.sortedInfo.order,
      render: (text, record) => {
        return record.status || t("general.labels.na");
      }
    },

    {
      title: t("jobs.fields.vehicle"),
      dataIndex: "vehicle",
      key: "vehicle",
      width: "15%",
      ellipsis: true,
      render: (text, record) => {
        return record.vehicle ? (
          <Link to={"/manage/vehicles/" + record.vehicle.id}>
            {record.vehicle.v_model_yr} {record.vehicle.v_make_desc}{" "}
            {record.vehicle.v_model_desc}
          </Link>
        ) : (
          t("jobs.errors.novehicle")
        );
      }
    },
    {
      title: t("vehicles.fields.plate_no"),
      dataIndex: "plate_no",
      key: "plate_no",
      width: "8%",
      ellipsis: true,
      sorter: (a, b) => alphaSort(a.vehicle.plate_no, b.vehicle.plate_no),
      sortOrder:
        state.sortedInfo.columnKey === "plate_no" && state.sortedInfo.order,
      render: (text, record) => {
        return record.vehicle.plate_no ? (
          <span>{record.vehicle.plate_no}</span>
        ) : (
          t("general.labels.unknown")
        );
      }
    },
    {
      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:
        state.sortedInfo.columnKey === "clm_no" && state.sortedInfo.order,
      render: (text, record) => {
        return record.clm_no ? (
          <span>{record.clm_no}</span>
        ) : (
          t("general.labels.unknown")
        );
      }
    },
    {
      title: t("jobs.fields.clm_total"),
      dataIndex: "clm_total",
      key: "clm_total",
      width: "10%",
      sorter: (a, b) => a.clm_total - b.clm_total,
      sortOrder:
        state.sortedInfo.columnKey === "clm_total" && state.sortedInfo.order,
      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) => {
        return record.owner_owing ? (
          <span>{record.owner_owing}</span>
        ) : (
          t("general.labels.unknown")
        );
      }
    }
  ];

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

  // const handleChange = event => {
  //   const { value } = event.target;
  //   setState({ ...state, filterinfo: { text: [value] } });
  // };

  const handleOnRowClick = record => {
    if (record) {
      if (record.id) {
        setSelectedJob(record.id);
        return;
      }
    }
    setSelectedJob(null);
  };

  return (
    <div>
      <Table
        loading={loading}
        title={() => {
          return (
            <div style={{ display: "flex" }}>
              <Button onClick={() => refetch()}>
                <SyncOutlined />
              </Button>
              <Input.Search
                placeholder="Search..."
                onChange={e => {
                  setSearchText(e.target.value);
                }}
                enterButton
              />
            </div>
          );
        }}
        size="small"
        pagination={{ position: "top" }}
        columns={columns.map(item => ({ ...item }))}
        rowKey="id"
        dataSource={jobs}
        rowSelection={{ selectedRowKeys: [selectedJob] }}
        onChange={handleTableChange}
        onRow={(record, rowIndex) => {
          return {
            onClick: event => {
              handleOnRowClick(record);
            }, // click row
            onDoubleClick: event => {}, // double click row
            onContextMenu: event => {}, // right button click row
            onMouseEnter: event => {}, // mouse enter row
            onMouseLeave: event => {} // mouse leave row
          };
        }}
      />
    </div>
  );
});
