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 { useMemo, 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 CurrencyFormatter from "../../utils/CurrencyFormatter";
import { onlyUnique } from "../../utils/arrayHelper";
import { pageLimit } from "../../utils/config";
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";

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

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

  const readyStatuses = useMemo(() => {
    if (bodyshop.md_ro_statuses.ready_statuses) return bodyshop.md_ro_statuses.ready_statuses;

    return bodyshop.md_ro_statuses.post_production_statuses.filter(
      (s) => s !== bodyshop.md_ro_statuses.default_invoiced && s !== bodyshop.md_ro_statuses.default_exported
    );
  }, [bodyshop.md_ro_statuses]);

  const { loading, error, data, refetch } = useQuery(QUERY_ALL_ACTIVE_JOBS, {
    variables: {
      statuses: readyStatuses,
      isConverted: true
    },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const [state, setState] = useState({ sortedInfo: {} });
  const [filter, setFilter] = useLocalStorage("filter_jobs_ready", 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) => {
    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) => alphaSort(a.ro_number, b.ro_number),
      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?.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(a.ownr_ln, b.ownr_ln),
      sortOrder: state.sortedInfo.columnKey === "owner" && state.sortedInfo.order,
      render: (text, record) => {
        return record.owner ? (
          <Link to={"/manage/owners/" + record.owner.id} 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) => alphaSort(a.status, b.status),
      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,
      render: (text, record) => {
        return record.vehicleid ? (
          <Link to={"/manage/vehicles/" + record.vehicleid} onClick={(e) => e.stopPropagation()}>
            {`${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",
      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,
      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: "jobs.labels.estimator",
      key: "estimator",
      ellipsis: true,
      responsive: ["xl"],
      filteredValue: filter?.estimator || null,
      filterSearch: true,
      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
      title={t("titles.bc.jobs-ready")}
      extra={
        <Space wrap>
          <span>({readyStatuses && readyStatuses.join(", ")})</span>
          <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: pageLimit }}
        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);
            }
          };
        }}
      />
    </Card>
  );
}

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