import { SyncOutlined } from "@ant-design/icons";
import { useQuery } from "@apollo/client/react";
import { Button, Card, Input, Space } from "antd";
import queryString from "query-string";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { QUERY_ALL_ACTIVE_JOBS } from "../../graphql/jobs.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { onlyUnique } from "../../utils/arrayHelper";
import { alphaSort } from "../../utils/sorters";
import AlertComponent from "../alert/alert.component";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";
import ResponsiveTable from "../responsive-table/responsive-table.component";

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

export function TechLookupJobsList({ bodyshop }) {
  const searchParams = queryString.parse(useLocation().search);
  const { selected } = searchParams;

  const { loading, error, data, refetch } = useQuery(QUERY_ALL_ACTIVE_JOBS, {
    variables: {
      statuses: bodyshop.md_ro_statuses.active_statuses || ["Open", "Open*"],
      isConverted: true
    },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" }
  });

  const { t } = useTranslation();
  const history = useNavigate();
  const [searchText, setSearchText] = useState("");

  if (error) return <AlertComponent title={error.message} type="error" />;

  const jobs = data
    ? searchText === ""
      ? data.jobs
      : data.jobs.filter(
          (j) =>
            (j.ro_number || "").toString().toLowerCase().includes(searchText.toLowerCase()) ||
            (j.ownr_fn || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.ownr_ln || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.ownr_co_nm || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.clm_no || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.plate_no || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.v_model_desc || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.v_make_desc || "").toLowerCase().includes(searchText.toLowerCase())
        )
    : [];

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

  const handleOnRowClick = (record) => {
    if (record) {
      if (record.id) {
        history({
          search: queryString.stringify({
            ...searchParams,
            selected: record.id
          })
        });
      }
    }
  };

  const columns = [
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "ro_number",
      key: "ro_number",
      sorter: (a, b) => alphaSort(a.ro_number, b.ro_number),
      sortOrder: state.sortedInfo.columnKey === "ro_number" && state.sortedInfo.order,

      render: (text, record) => record.ro_number || t("general.labels.na")
    },
    {
      title: t("jobs.fields.owner"),
      dataIndex: "owner",
      key: "owner",
      sorter: (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),
      sortOrder: state.sortedInfo.columnKey === "owner" && state.sortedInfo.order,
      ellipsis: true,
      render: (text, record) => (
        <span>
          <OwnerNameDisplay ownerObject={record} />
        </span>
      )
    },
    {
      title: t("jobs.fields.status"),
      dataIndex: "status",
      key: "status",
      sorter: (a, b) => alphaSort(a.status, b.status),
      sortOrder: state.sortedInfo.columnKey === "status" && state.sortedInfo.order,
      filters:
        (jobs &&
          jobs
            .map((j) => j.status)
            .filter(onlyUnique)
            .map((s) => {
              return {
                text: s || t("dashboard.errors.status"),
                value: [s]
              };
            })) ||
        [],
      onFilter: (value, record) => value.includes(record.status),
      render: (text, record) => {
        return record.status || t("general.labels.na");
      }
    },

    {
      title: t("jobs.fields.vehicle"),
      dataIndex: "vehicle",
      key: "vehicle",
      ellipsis: true,
      render: (text, record) => (
        <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",
      sorter: (a, b) => alphaSort(a.plate_no, b.plate_no),
      sortOrder: state.sortedInfo.columnKey === "plate_no" && state.sortedInfo.order,
      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: (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");
      }
    }
  ];

  return (
    <Card
      extra={
        <Space wrap>
          <Button onClick={() => refetch()} icon={<SyncOutlined />} />
          <Input.Search
            placeholder={t("general.labels.search")}
            onChange={(e) => {
              setSearchText(e.target.value);
            }}
            value={searchText}
            enterButton
          />
        </Space>
      }
    >
      <ResponsiveTable
        loading={loading}
        pagination={false}
        columns={columns}
        mobileColumnKeys={["ro_number", "owner", "status", "vehicle"]}
        rowKey="id"
        dataSource={jobs}
        scroll={{ x: true }}
        rowSelection={{
          onSelect: (record) => {
            handleOnRowClick(record);
          },
          selectedRowKeys: [selected],
          type: "radio"
        }}
        onChange={handleTableChange}
        onRow={(record) => {
          return {
            onClick: () => {
              handleOnRowClick(record);
            }
          };
        }}
      />
    </Card>
  );
}

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