import { EditFilled, SyncOutlined } from "@ant-design/icons";
import { Button, Card, Checkbox, Input, Space, Table } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectJobReadOnly } from "../../redux/application/application.selectors";
import { setModalContext } from "../../redux/modals/modals.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { DateFormatter } from "../../utils/DateFormatter";
import { alphaSort, dateSort } from "../../utils/sorters";
import { TemplateList } from "../../utils/TemplateConstants";
import BillDeleteButton from "../bill-delete-button/bill-delete-button.component";
import BillDetailEditReturnComponent from "../bill-detail-edit/bill-detail-edit-return.component";
import PrintWrapperComponent from "../print-wrapper/print-wrapper.component";

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

const mapDispatchToProps = (dispatch) => ({
  setPartsOrderContext: (context) =>
    dispatch(setModalContext({ context: context, modal: "partsOrder" })),
  setBillEnterContext: (context) =>
    dispatch(setModalContext({ context: context, modal: "billEnter" })),
  setReconciliationContext: (context) =>
    dispatch(setModalContext({ context: context, modal: "reconciliation" })),
});

export function BillsListTableComponent({
  bodyshop,
  jobRO,
  job,
  billsQuery,
  handleOnRowClick,
  setPartsOrderContext,
  setBillEnterContext,
  setReconciliationContext,
}) {
  const { t } = useTranslation();

  const [state, setState] = useState({
    sortedInfo: {},
  });
  // const search = queryString.parse(useLocation().search);
  // const selectedBill = search.billid;
  const [searchText, setSearchText] = useState("");

  const Templates = TemplateList("bill");
  const bills = billsQuery.data ? billsQuery.data.bills : [];
  const { refetch } = billsQuery;
  const recordActions = (record, showView = false) => (
    <Space wrap>
      {showView && (
        <Button onClick={() => handleOnRowClick(record)}>
          <EditFilled />
        </Button>
      )}
      <BillDeleteButton bill={record} />
      <BillDetailEditReturnComponent
        data={{ bills_by_pk: { ...record, jobid: job.id } }}
        disabled={
          record.is_credit_memo ||
          record.vendorid === bodyshop.inhousevendorid ||
          jobRO
        }
      />

      {record.isinhouse && (
        <PrintWrapperComponent
          templateObject={{
            name: Templates.inhouse_invoice.key,
            variables: { id: record.id },
          }}
          messageObject={{ subject: Templates.inhouse_invoice.subject }}
        />
      )}
    </Space>
  );
  const columns = [
    {
      title: t("bills.fields.vendorname"),
      dataIndex: "vendorname",
      key: "vendorname",
      sorter: (a, b) => alphaSort(a.vendor.name, b.vendor.name),
      sortOrder:
        state.sortedInfo.columnKey === "vendorname" && state.sortedInfo.order,
      render: (text, record) => <span>{record.vendor.name}</span>,
    },
    {
      title: t("bills.fields.invoice_number"),
      dataIndex: "invoice_number",
      key: "invoice_number",
      sorter: (a, b) => alphaSort(a.invoice_number, b.invoice_number),
      sortOrder:
        state.sortedInfo.columnKey === "invoice_number" &&
        state.sortedInfo.order,
    },
    {
      title: t("bills.fields.date"),
      dataIndex: "date",
      key: "date",
      sorter: (a, b) => dateSort(a.date, b.date),
      sortOrder:
        state.sortedInfo.columnKey === "date" && state.sortedInfo.order,
      render: (text, record) => <DateFormatter>{record.date}</DateFormatter>,
    },
    {
      title: t("bills.fields.total"),
      dataIndex: "total",
      key: "total",
      sorter: (a, b) => a.total - b.total,
      sortOrder:
        state.sortedInfo.columnKey === "total" && state.sortedInfo.order,
      render: (text, record) => (
        <CurrencyFormatter>{record.total}</CurrencyFormatter>
      ),
    },
    {
      title: t("bills.fields.is_credit_memo"),
      dataIndex: "is_credit_memo",
      key: "is_credit_memo",
      sorter: (a, b) => a.is_credit_memo - b.is_credit_memo,
      sortOrder:
        state.sortedInfo.columnKey === "is_credit_memo" &&
        state.sortedInfo.order,
      render: (text, record) => <Checkbox checked={record.is_credit_memo} />,
    },
    {
      title: t("bills.fields.exported"),
      dataIndex: "exported",
      key: "exported",
      sorter: (a, b) => a.exported - b.exported,
      sortOrder:
        state.sortedInfo.columnKey === "exported" && state.sortedInfo.order,
      render: (text, record) => <Checkbox checked={record.exported} />,
    },
    {
      title: t("general.labels.actions"),
      dataIndex: "actions",
      key: "actions",
      render: (text, record) => recordActions(record, true),
    },
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
  };

  const filteredBills = bills
    ? searchText === ""
      ? bills
      : bills.filter(
          (b) =>
            (b.invoice_number || "")
              .toLowerCase()
              .includes(searchText.toLowerCase()) ||
            (b.vendor.name || "")
              .toLowerCase()
              .includes(searchText.toLowerCase()) ||
            (b.total || "")
              .toString()
              .toLowerCase()
              .includes(searchText.toLowerCase())
        )
    : [];

  return (
    <Card
      title={t("bills.labels.bills")}
      extra={
        <Space wrap>
          <Button onClick={() => refetch()}>
            <SyncOutlined />
          </Button>
          {job && job.converted ? (
            <>
              <Button
                onClick={() => {
                  setBillEnterContext({
                    actions: { refetch: billsQuery.refetch },
                    context: {
                      job,
                    },
                  });
                }}
              >
                {t("jobs.actions.postbills")}
              </Button>
              <Button
                onClick={() => {
                  setReconciliationContext({
                    actions: { refetch: billsQuery.refetch },
                    context: {
                      job,
                      bills: (billsQuery.data && billsQuery.data.bills) || [],
                    },
                  });
                }}
              >
                {t("jobs.actions.reconcile")}
              </Button>
            </>
          ) : null}

          <Input.Search
            placeholder={t("general.labels.search")}
            value={searchText}
            onChange={(e) => {
              e.preventDefault();
              setSearchText(e.target.value);
            }}
          />
        </Space>
      }
    >
      <Table
        loading={billsQuery.loading}
        scroll={{
          x: true, // y: "50rem"
        }}
        columns={columns}
        rowKey="id"
        dataSource={filteredBills}
        onChange={handleTableChange}
      />
    </Card>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(BillsListTableComponent);
