import { SyncOutlined } from "@ant-design/icons";
import { useQuery } from "@apollo/client";
import { Button, Card, Input, Space, Table } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link, useHistory } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import AlertComponent from "../../components/alert/alert.component";
import JobRemoveFromPartsQueue from "../../components/job-remove-from-parst-queue/job-remove-from-parts-queue.component";
import { QUERY_PARTS_QUEUE } from "../../graphql/jobs.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { onlyUnique } from "../../utils/arrayHelper";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { TimeAgoFormatter } from "../../utils/DateFormatter";
import { alphaSort } from "../../utils/sorters";
import { useLocation } from "react-router-dom";
import queryString from "query-string";
import _ from "lodash";

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

export function PartsQueuePageComponent({ bodyshop }) {
  const searchParams = queryString.parse(useLocation().search);
  const { page, sortcolumn, sortorder, statusFilters } = searchParams;
  const history = useHistory();

  const { loading, error, data, refetch } = useQuery(QUERY_PARTS_QUEUE, {
    variables: {
      offset: page ? (page - 1) * 25 : 0,
      limit: 25,
      statuses: (statusFilters && JSON.parse(statusFilters)) ||
        bodyshop.md_ro_statuses.active_statuses || ["Open", "Open*"],
      order: [
        {
          [sortcolumn || "updated_at"]: sortorder
            ? sortorder === "descend"
              ? "desc"
              : "asc"
            : "desc",
        },
      ],
    },
  });

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

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

  const jobs = data
    ? searchText === ""
      ? data.jobs
      : data.jobs.filter(
          (j) =>
            (j.ro_number || "")
              .toString()
              .toLowerCase()
              .includes(searchText.toLowerCase()) ||
            (j.ownr_co_nm || "")
              .toLowerCase()
              .includes(searchText.toLowerCase()) ||
            (j.ownr_fn || "")
              .toLowerCase()
              .includes(searchText.toLowerCase()) ||
            (j.ownr_ln || "")
              .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) => {
    searchParams.page = pagination.current;
    searchParams.sortcolumn = sorter.columnKey;
    searchParams.sortorder = sorter.order;
    if (filters.status) {
      searchParams.statusFilters = JSON.stringify(
        _.flattenDeep(filters.status)
      );
    } else {
      delete searchParams.statusFilters;
    }
    history.push({ search: queryString.stringify(searchParams) });
  };

  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: 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",
      // sorter: (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),
      // sortOrder: sortcolumn === "owner" && sortorder,
      render: (text, record) => {
        return record.ownerid ? (
          <Link to={"/manage/owners/" + record.ownerid}>
            {`${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.status"),
      dataIndex: "status",
      key: "status",
      sorter: (a, b) => alphaSort(a.status, b.status),
      sortOrder: sortcolumn === "status" && sortorder,
      filters:
        (jobs &&
          jobs
            .map((j) => j.status)
            .filter(onlyUnique)
            .map((s) => {
              return {
                text: s || "No 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) => {
        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",
      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",
      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.clm_total"),
      dataIndex: "clm_total",
      key: "clm_total",
      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.updated_at"),
      dataIndex: "updated_at",
      key: "updated_at",
      render: (text, record) => (
        <TimeAgoFormatter>{record.updated_at}</TimeAgoFormatter>
      ),
    },
    {
      title: t("general.labels.actions"),
      dataIndex: "actions",
      key: "actions",
      render: (text, record) => (
        <JobRemoveFromPartsQueue jobId={record.id} refetch={refetch} />
      ),
    },
  ];

  return (
    <Card
      extra={
        <Space wrap>
          <Button onClick={() => refetch()}>
            <SyncOutlined />
          </Button>
          <Input.Search
            className="imex-table-header__search"
            placeholder={t("general.labels.search")}
            onChange={(e) => {
              setSearchText(e.target.value);
            }}
            value={searchText}
            enterButton
          />
        </Space>
      }
    >
      <Table
        loading={loading}
        pagination={{
          position: "top",
          pageSize: 25,
          current: parseInt(page || 1),
          total: data && data.jobs_aggregate.aggregate.count,
        }}
        columns={columns}
        rowKey="id"
        dataSource={jobs}
        style={{ height: "100%" }}
        scroll={{ x: true }}
        onChange={handleTableChange}
      />
    </Card>
  );
}

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