import { EditFilled, FileAddFilled, SyncOutlined } from "@ant-design/icons";
import { Button, Card, Input, Space, Typography } from "antd";
import queryString from "query-string";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { setModalContext } from "../../redux/modals/modals.actions";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import InventoryBillRo from "../inventory-bill-ro/inventory-bill-ro.component";
import InventoryLineDelete from "../inventory-line-delete/inventory-line-delete.component";
import { pageLimit } from "../../utils/config";
import ResponsiveTable from "../responsive-table/responsive-table.component";

const mapStateToProps = createStructuredSelector({});
const mapDispatchToProps = (dispatch) => ({
  setInventoryUpsertContext: (context) => dispatch(setModalContext({ context: context, modal: "inventoryUpsert" }))
});

export function JobsList({ refetch, loading, jobs, total, setInventoryUpsertContext }) {
  const search = queryString.parse(useLocation().search);
  const { page, sortcolumn, sortorder } = search;
  const history = useNavigate();

  const { t } = useTranslation();
  const columns = [
    {
      title: t("billlines.fields.line_desc"),
      dataIndex: "line_desc",
      key: "line_desc",

      sorter: true, //(a, b) => alphaSort(a.line_desc, b.line_desc),
      sortOrder: sortcolumn === "line_desc" && sortorder,
      render: (text, record) =>
        record.billline?.bill?.job ? (
          <div>
            <div>{text}</div>
            <strong>{`(${record.billline?.bill?.job?.v_model_yr} ${record.billline?.bill?.job?.v_make_desc} ${record.billline?.bill?.job?.v_model_desc})`}</strong>
          </div>
        ) : (
          text
        )
    },
    {
      title: t("inventory.labels.frombillinvoicenumber"),
      dataIndex: "vendorname",
      key: "vendorname",
      ellipsis: true,
      //sorter: true, // (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),

      //sortOrder: sortcolumn === "ownr_ln" && sortorder,
      render: (text, record) =>
        ((record.billline?.bill?.invoice_number || "") + " " + (record.manualinvoicenumber || "")).trim()
    },
    {
      title: t("inventory.labels.fromvendor"),
      dataIndex: "vendorname",
      key: "vendorname",
      ellipsis: true,
      //sorter: true, // (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),

      //sortOrder: sortcolumn === "ownr_ln" && sortorder,
      render: (text, record) => ((record.billline?.bill?.vendor?.name || "") + " " + (record.manualvendor || "")).trim()
    },
    {
      title: t("billlines.fields.actual_price"),
      dataIndex: "actual_price",
      key: "actual_price",

      render: (text, record) => <CurrencyFormatter>{record.actual_price}</CurrencyFormatter>
    },
    {
      title: t("billlines.fields.actual_cost"),
      dataIndex: "actual_cost",
      key: "actual_cost",

      render: (text, record) => <CurrencyFormatter>{record.actual_cost}</CurrencyFormatter>
    },
    {
      title: t("inventory.fields.comment"),
      dataIndex: "comment",
      key: "comment"
    },
    {
      title: t("inventory.labels.consumedbyjob"),
      dataIndex: "consumedbyjob",
      key: "consumedbyjob",

      ellipsis: true,
      render: (text, record) =>
        record.bill?.job?.ro_number ? (
          <Link to={`/manage/jobs/${record.bill?.job?.id}`}>{record.bill?.job?.ro_number}</Link>
        ) : (
          <InventoryBillRo inventoryline={record} />
        )
    },
    {
      title: t("general.labels.actions"),
      dataIndex: "actions",
      key: "actions",

      ellipsis: true,
      render: (text, record) => (
        <Space wrap>
          <Button
            onClick={() => {
              setInventoryUpsertContext({
                actions: { refetch: refetch },
                context: {
                  existingInventory: record
                }
              });
            }}
            icon={<EditFilled />}
          />

          <InventoryLineDelete inventoryline={record} refetch={refetch} />
        </Space>
      )
    }
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    const updatedSearch = {
      ...search,
      page: pagination.current,
      sortcolumn: sorter.column && sorter.column.key,
      sortorder: sorter.order
    };
    history({ search: queryString.stringify(updatedSearch) });
  };

  return (
    <Card
      extra={
        <Space wrap>
          {search.search && (
            <>
              <Typography.Title level={4}>
                {t("general.labels.searchresults", { search: search.search })}
              </Typography.Title>
              <Button
                onClick={() => {
                  delete search.search;
                  history({ search: queryString.stringify(search) });
                }}
              >
                {t("general.actions.clear")}
              </Button>
            </>
          )}
          <Button
            onClick={() => {
              setInventoryUpsertContext({
                actions: { refetch: refetch },
                context: {}
              });
            }}
            icon={<FileAddFilled />}
          />

          <Button
            onClick={() => {
              const updatedSearch = { ...search };
              if (updatedSearch.showall) {
                delete updatedSearch.showall;
              } else {
                updatedSearch.showall = true;
              }
              history({ search: queryString.stringify(updatedSearch) });
            }}
          >
            {search.showall ? t("inventory.labels.showavailable") : t("inventory.labels.showall")}
          </Button>

          <Button onClick={() => refetch()} icon={<SyncOutlined />} />

          <Input.Search
            placeholder={search.search || t("general.labels.search")}
            onSearch={(value) => {
              const updatedSearch = { ...search, search: value };
              history({ search: queryString.stringify(updatedSearch) });
            }}
            enterButton
          />
        </Space>
      }
    >
      <ResponsiveTable
        loading={loading}
        pagination={{ placement: "top", pageSize: pageLimit, current: parseInt(page || 1), total: total }}
        columns={columns}
        mobileColumnKeys={["line_desc", "actual_price", "consumedbyjob", "actions"]}
        rowKey="id"
        dataSource={jobs}
        onChange={handleTableChange}
      />
    </Card>
  );
}

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