import { SyncOutlined } from "@ant-design/icons";
import { Button, Card, Input, Space, Table, Typography } from "antd";
import axios from "axios";
import _ from "lodash";
import queryString from "query-string";
import { useEffect, 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 { selectBodyshop } from "../../redux/user/user.selectors";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { pageLimit } from "../../utils/config";
import { alphaSort, statusSort } from "../../utils/sorters";
import useLocalStorage from "../../utils/useLocalStorage";
import StartChatButton from "../chat-open-button/chat-open-button.component";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";
import { logImEXEvent } from "../../firebase/firebase.utils";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});

export function JobsList({ bodyshop, refetch, loading, jobs, total }) {
  const search = queryString.parse(useLocation().search);
  const [openSearchResults, setOpenSearchResults] = useState([]);
  const [searchLoading, setSearchLoading] = useState(false);
  const [filter, setFilter] = useLocalStorage("filter_jobs_all", null);
  const { page, sortcolumn, sortorder } = search;
  const history = useNavigate();

  const { t } = useTranslation();
  const columns = [
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "ro_number",
      key: "ro_number",
      sorter: search?.search
        ? (a, b) =>
            parseInt((a.ro_number || "0").replace(/\D/g, "")) - parseInt((b.ro_number || "0").replace(/\D/g, ""))
        : true,
      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: "ownr_ln",
      key: "ownr_ln",
      ellipsis: true,
      //sorter: true, // (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),
      //sortOrder: sortcolumn === "ownr_ln" && sortorder,
      render: (text, record) => {
        return record.ownerid ? (
          <Link to={"/manage/owners/" + record.ownerid}>
            <OwnerNameDisplay ownerObject={record} />
          </Link>
        ) : (
          <span>
            <OwnerNameDisplay ownerObject={record} />
          </span>
        );
      }
    },
    {
      title: t("jobs.fields.ownr_ph1"),
      dataIndex: "ownr_ph1",
      key: "ownr_ph1",
      ellipsis: true,
      render: (text, record) => <StartChatButton 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,
      render: (text, record) => <StartChatButton type={record.ownr_ph2_ty} phone={record.ownr_ph2} jobid={record.id} />
    },
    {
      title: t("jobs.fields.status"),
      dataIndex: "status",
      key: "status",

      ellipsis: true,
      sorter: search?.search ? (a, b) => statusSort(a.status, b.status, bodyshop.md_ro_statuses.active_statuses) : true,
      sortOrder: sortcolumn === "status" && sortorder,
      render: (text, record) => {
        return record.status || t("general.labels.na");
      },
      filteredValue: filter?.status || null,
      filters: bodyshop.md_ro_statuses.statuses.map((s) => {
        return { text: s, value: [s] };
      }),
      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}>
            {`${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,
      sorter: search?.search ? (a, b) => alphaSort(a.plate_no, b.plate_no) : true,
      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: search?.search ? (a, b) => alphaSort(a.clm_no, b.clm_no) : true,
      sortOrder: sortcolumn === "clm_no" && sortorder,
      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
    },
    {
      title: t("jobs.fields.clm_total"),
      dataIndex: "clm_total",
      key: "clm_total",
      sorter: search?.search ? (a, b) => a.clm_total - b.clm_total : true,
      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.owner_owing"),
      dataIndex: "owner_owing",
      key: "owner_owing",
      render: (text, record) => <CurrencyFormatter>{record.owner_owing}</CurrencyFormatter>
    },
    {
      title: t("jobs.fields.comment"),
      dataIndex: "comment",
      key: "comment",
      ellipsis: true
    }
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    search.page = pagination.current;
    search.sortcolumn = sorter.column && sorter.column.key;
    search.sortorder = sorter.order;
    if (filters.status) {
      search.statusFilters = JSON.stringify(_.flattenDeep(filters.status));
    } else {
      delete search.statusFilters;
    }
    setFilter(filters);
    history({ search: queryString.stringify(search) });
    logImEXEvent("jobs_all_list_sort_filter", { pagination, filters, sorter });
  };

  useEffect(() => {
    if (search.search && search.search.trim() !== "") {
      searchJobs();
    }
  }, []);

  async function searchJobs(value) {
    try {
      setSearchLoading(true);
      const searchData = await axios.post("/search", {
        search: value || search.search,
        index: "jobs"
      });
      setOpenSearchResults(searchData.data.hits.hits.map((s) => s._source));
    } catch (error) {
      console.log("Error while fetching search results", error);
    } finally {
      setSearchLoading(false);
    }
  }

  return (
    <Card
      id="all-jobs-list"
      title={t("titles.bc.jobs-all")}
      extra={
        <Space wrap>
          {search.search && (
            <>
              <Typography.Title level={4}>
                {t("general.labels.searchresults", { search: search.search })}
              </Typography.Title>
              <Button
                onClick={() => {
                  delete search.search;
                  delete search.page;
                  history({ search: queryString.stringify(search) });
                }}
              >
                {t("general.actions.clear")}
              </Button>
            </>
          )}
          <Button onClick={() => refetch()}>
            <SyncOutlined />
          </Button>
          <Input.Search
            placeholder={search.search || t("general.labels.search")}
            onSearch={(value) => {
              search.search = value;
              history({ search: queryString.stringify(search) });
              searchJobs(value);
            }}
            loading={loading || searchLoading}
            enterButton
          />
        </Space>
      }
    >
      <Table
        loading={loading || searchLoading}
        pagination={
          search?.search
            ? {
                pageSize: pageLimit,
                showSizeChanger: false
              }
            : {
                pageSize: pageLimit,
                current: parseInt(page || 1),
                total: total,
                showSizeChanger: false
              }
        }
        columns={columns}
        rowKey="id"
        dataSource={search?.search ? openSearchResults : jobs}
        onChange={handleTableChange}
        id="all-jobs-list-table"
      />
    </Card>
  );
}

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