import { BranchesOutlined, ExclamationCircleFilled, PauseCircleOutlined, SyncOutlined } from "@ant-design/icons";
import { useQuery } from "@apollo/client/react";
import { Button, Card, Input, Space, Tooltip } from "antd";
import queryString from "query-string";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link, 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 CurrencyFormatter from "../../utils/CurrencyFormatter";
import { alphaSort, statusSort } from "../../utils/sorters";
import useLocalStorage from "../../utils/useLocalStorage";
import AlertComponent from "../alert/alert.component";
import ChatOpenButton from "../chat-open-button/chat-open-button.component";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { OwnerNameDisplayFunction } from "./../owner-name-display/owner-name-display.component";
import { logImEXEvent } from "../../firebase/firebase.utils";

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

const mapDispatchToProps = () => ({});

export function JobsList({ 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*"]
    },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const [state, setState] = useState({ sortedInfo: {} });
  const [filter, setFilter] = useLocalStorage("filter_jobs_list", null);

  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_co_nm || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.comments || "").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.est_ct_fn || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.est_ct_ln || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.v_make_desc || "").toLowerCase().includes(searchText.toLowerCase())
        )
    : [];

  const handleTableChange = (pagination, filters, sorter) => {
    logImEXEvent("jobs_list_sort_filter", { pagination, filters, sorter });
    setState({ ...state, sortedInfo: sorter });
    setFilter(filters);
  };

  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) =>
        parseInt((a.ro_number || "0").replace(/\D/g, "")) - parseInt((b.ro_number || "0").replace(/\D/g, "")),
      sortOrder: state.sortedInfo.columnKey === "ro_number" && state.sortedInfo.order,

      render: (text, record) => (
        <Link to={"/manage/jobs/" + record.id} onClick={(e) => e.stopPropagation()}>
          <Space>
            {record.ro_number || t("general.labels.na")}
            {record.production_vars && record.production_vars.alert ? (
              <ExclamationCircleFilled className="production-alert" />
            ) : null}
            {record.suspended && <PauseCircleOutlined style={{ color: "orangered" }} />}
            {record.iouparent && (
              <Tooltip title={t("jobs.labels.iou")}>
                <BranchesOutlined style={{ color: "orangered" }} />
              </Tooltip>
            )}
          </Space>
        </Link>
      )
    },
    {
      title: t("jobs.fields.owner"),
      dataIndex: "owner",
      key: "owner",
      ellipsis: true,

      responsive: ["md"],
      sorter: (a, b) => alphaSort(OwnerNameDisplayFunction(a), OwnerNameDisplayFunction(b)),
      sortOrder: state.sortedInfo.columnKey === "owner" && state.sortedInfo.order,
      render: (text, record) => {
        return record.ownerid ? (
          <Link to={"/manage/owners/" + record.ownerid} onClick={(e) => e.stopPropagation()}>
            <OwnerNameDisplay ownerObject={record} />
          </Link>
        ) : (
          <span>
            <OwnerNameDisplay ownerObject={record} />
          </span>
        );
      }
    },
    {
      title: t("jobs.fields.ownr_ph1"),
      dataIndex: "ownr_ph1",
      key: "ownr_ph1",
      ellipsis: true,
      responsive: ["md"],
      render: (text, record) => <ChatOpenButton type={record.ownr_ph1_ty} phone={record.ownr_ph1} jobid={record.id} />
    },
    {
      title: t("jobs.fields.ownr_ph2"),
      dataIndex: "ownr_ph2",
      key: "ownr_ph2",
      ellipsis: true,
      responsive: ["md"],
      render: (text, record) => <ChatOpenButton type={record.ownr_ph2_ty} phone={record.ownr_ph2} jobid={record.id} />
    },

    {
      title: t("jobs.fields.status"),
      dataIndex: "status",
      key: "status",
      ellipsis: true,

      sorter: (a, b) => statusSort(a.status, b.status, bodyshop.md_ro_statuses.active_statuses),
      sortOrder: state.sortedInfo.columnKey === "status" && state.sortedInfo.order,
      filteredValue: filter?.status || null,
      filters:
        (jobs &&
          jobs
            .map((j) => j.status)
            .filter(onlyUnique)
            .map((s) => {
              return {
                text: s || t("dashboard.errors.status"),
                value: [s]
              };
            })
            .sort((a, b) => statusSort(a.text, b.text, bodyshop.md_ro_statuses.active_statuses))) ||
        [],
      onFilter: (value, record) => value.includes(record.status)
    },
    {
      title: t("jobs.fields.vehicle"),
      dataIndex: "vehicle",
      key: "vehicle",
      ellipsis: true,
      sorter: (a, b) =>
        alphaSort(
          `${a.v_model_yr || ""} ${a.v_make_desc || ""} ${a.v_model_desc || ""}`,
          `${b.v_model_yr || ""} ${b.v_make_desc || ""} ${b.v_model_desc || ""}`
        ),
      sortOrder: state.sortedInfo.columnKey === "vehicle" && state.sortedInfo.order,
      render: (text, record) => {
        const vehicleLabel =
          `${record.v_model_yr || ""} ${record.v_make_desc || ""} ${record.v_model_desc || ""}`.trim();

        return record.vehicleid ? (
          <Link to={"/manage/vehicles/" + record.vehicleid} onClick={(e) => e.stopPropagation()}>
            <span className="ellipses">{vehicleLabel}</span>
          </Link>
        ) : (
          <span className="ellipses">{vehicleLabel}</span>
        );
      }
    },
    {
      title: t("vehicles.fields.plate_no"),
      dataIndex: "plate_no",
      key: "plate_no",
      ellipsis: true,

      responsive: ["md"],
      sorter: (a, b) => alphaSort(a.plate_no, b.plate_no),
      sortOrder: state.sortedInfo.columnKey === "plate_no" && state.sortedInfo.order
    },
    {
      title: t("jobs.fields.clm_no"),
      dataIndex: "clm_no",
      key: "clm_no",
      ellipsis: true,
      responsive: ["md"],
      sorter: (a, b) => alphaSort(a.clm_no, b.clm_no),
      sortOrder: state.sortedInfo.columnKey === "clm_no" && state.sortedInfo.order,
      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,
      sorter: (a, b) => alphaSort(a.ins_co_nm, b.ins_co_nm),
      sortOrder: state.sortedInfo.columnKey === "ins_co_nm" && state.sortedInfo.order,
      filteredValue: filter?.ins_co_nm || null,
      filters:
        (jobs &&
          jobs
            .map((j) => j.ins_co_nm)
            .filter(onlyUnique)
            .map((s) => {
              return {
                text: s || "No Ins. Co.*",
                value: [s]
              };
            })
            .sort((a, b) => alphaSort(a.text, b.text))) ||
        [],
      onFilter: (value, record) => value.includes(record.ins_co_nm),
      responsive: ["md"]
    },
    {
      title: t("jobs.fields.clm_total"),
      dataIndex: "clm_total",
      key: "clm_total",
      responsive: ["md"],
      ellipsis: true,

      sorter: (a, b) => a.clm_total - b.clm_total,
      sortOrder: state.sortedInfo.columnKey === "clm_total" && state.sortedInfo.order,
      render: (text, record) => <CurrencyFormatter>{record.clm_total}</CurrencyFormatter>
    },
    {
      title: t("jobs.labels.estimator"),
      dataIndex: "estimator",
      key: "estimator",
      ellipsis: true,
      responsive: ["xl"],
      sorter: (a, b) =>
        alphaSort(
          `${a.est_ct_fn || ""} ${a.est_ct_ln || ""}`.trim(),
          `${b.est_ct_fn || ""} ${b.est_ct_ln || ""}`.trim()
        ),
      sortOrder: state.sortedInfo.columnKey === "estimator" && state.sortedInfo.order,
      filterSearch: true,
      filteredValue: filter?.estimator || null,
      filters:
        (jobs &&
          jobs
            .map((j) => `${j.est_ct_fn || ""} ${j.est_ct_ln || ""}`.trim())
            .filter(onlyUnique)
            .map((s) => {
              return {
                text: s || "No Estimator*",
                value: [s]
              };
            })
            .sort((a, b) => alphaSort(a.text, b.text))) ||
        [],
      onFilter: (value, record) => value.includes(`${record.est_ct_fn || ""} ${record.est_ct_ln || ""}`.trim()),
      render: (text, record) => `${record.est_ct_fn || ""} ${record.est_ct_ln || ""}`.trim()
    },
    {
      title: t("jobs.fields.comment"),
      dataIndex: "comment",
      key: "comment",
      ellipsis: true,
      responsive: ["md"]
    }
    // {
    //   title: t("jobs.fields.owner_owing"),
    //   dataIndex: "owner_owing",
    //   key: "owner_owing",
    //   responsive: ["md"],
    //   render: (text, record) => (
    //     <CurrencyFormatter>{record.owner_owing}</CurrencyFormatter>
    //   ),
    // },
  ];

  return (
    <Card
      id="active-jobs-list"
      title={t("titles.bc.jobs-active")}
      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={{ defaultPageSize: 50 }}
        columns={columns}
        rowKey="id"
        dataSource={jobs}
        mobileColumnKeys={["ro_number", "owner", "status", "vehicle"]}
        rowSelection={{
          onSelect: (record) => {
            handleOnRowClick(record);
          },
          selectedRowKeys: [selected],
          type: "radio"
        }}
        onChange={handleTableChange}
        onRow={(record) => {
          return {
            onClick: () => {
              handleOnRowClick(record);
            }
          };
        }}
        id="active-jobs-list-table"
      />
    </Card>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(JobsList);
