import { Input, Table, Checkbox, Card, Space } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { alphaSort, dateSort } from "../../utils/sorters";
import PayableExportButton from "../payable-export-button/payable-export-button.component";
import PayableExportAll from "../payable-export-all-button/payable-export-all-button.component";
import { DateFormatter } from "../../utils/DateFormatter";
import queryString from "query-string";
import { logImEXEvent } from "../../firebase/firebase.utils";
import QboAuthorizeComponent from "../qbo-authorize/qbo-authorize.component";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import ExportLogsCountDisplay from "../export-logs-count-display/export-logs-count-display.component";
import BillMarkSelectedExported from "../payable-mark-selected-exported/payable-mark-selected-exported.component";
import {pageLimit} from "../../utils/config";

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

const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});

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

export function AccountingPayablesTableComponent({
  bodyshop,
  loading,
  bills,
  refetch,
}) {
  const { t } = useTranslation();
  const [selectedBills, setSelectedBills] = useState([]);
  const [transInProgress, setTransInProgress] = useState(false);
  const [state, setState] = useState({
    sortedInfo: {},
    search: "",
  });

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

  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) => (
        <Link
          to={{
            pathname: `/manage/shop/vendors`,
            search: queryString.stringify({ selectedvendor: record.vendor.id }),
          }}
        >
          {record.vendor.name}
        </Link>
      ),
    },
    {
      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,
      render: (text, record) => (
        <Link
          to={{
            pathname: `/manage/bills`,
            search: queryString.stringify({
              billid: record.id,
              vendorid: record.vendor.id,
            }),
          }}
        >
          {record.invoice_number}
        </Link>
      ),
    },
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "ro_number",
      key: "ro_number",
      sorter: (a, b) => alphaSort(a.job.ro_number, b.job.ro_number),
      sortOrder:
        state.sortedInfo.columnKey === "ro_number" && state.sortedInfo.order,
      render: (text, record) => (
        <Link to={`/manage/jobs/${record.job.id}`}>{record.job.ro_number}</Link>
      ),
    },
    {
      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 disabled checked={record.is_credit_memo} />
      ),
    },
    {
      title: t("exportlogs.labels.attempts"),
      dataIndex: "attempts",
      key: "attempts",

      render: (text, record) => (
        <ExportLogsCountDisplay logs={record.exportlogs} />
      ),
    },
    {
      title: t("general.labels.actions"),
      dataIndex: "actions",
      key: "actions",
      sorter: (a, b) => a.clm_total - b.clm_total,

      render: (text, record) => (
        <PayableExportButton
          billId={record.id}
          disabled={transInProgress || !!record.exported}
          loadingCallback={setTransInProgress}
          setSelectedBills={setSelectedBills}
          refetch={refetch}
        />
      ),
    },
  ];

  const handleSearch = (e) => {
    setState({ ...state, search: e.target.value });
    logImEXEvent("accounting_payables_table_search");
  };

  const dataSource = state.search
    ? bills.filter(
        (v) =>
          (v.vendor.name || "")
            .toLowerCase()
            .includes(state.search.toLowerCase()) ||
          (v.invoice_number || "")
            .toLowerCase()
            .includes(state.search.toLowerCase())
      )
    : bills;

  return (
    <Card
      extra={
        <Space wrap>
          <BillMarkSelectedExported
            billids={selectedBills}
            disabled={transInProgress || selectedBills.length === 0}
            loadingCallback={setTransInProgress}
            completedCallback={setSelectedBills}
            refetch={refetch}
          />
          <PayableExportAll
            billids={selectedBills}
            disabled={transInProgress || selectedBills.length === 0}
            loadingCallback={setTransInProgress}
            completedCallback={setSelectedBills}
            refetch={refetch}
          />
          {bodyshop.accountingconfig && bodyshop.accountingconfig.qbo && (
            <QboAuthorizeComponent />
          )}
          <Input
            value={state.search}
            onChange={handleSearch}
            placeholder={t("general.labels.search")}
            allowClear
          />
        </Space>
      }
    >
      <Table
        loading={loading}
        dataSource={dataSource}
        pagination={{ position: "top", pageSize: pageLimit }}
        columns={columns}
        rowKey="id"
        onChange={handleTableChange}
        rowSelection={{
          onSelectAll: (selected, selectedRows) =>
            setSelectedBills(selectedRows.map((i) => i.id)),
          onSelect: (record, selected, selectedRows, nativeEvent) => {
            setSelectedBills(selectedRows.map((i) => i.id));
          },
          getCheckboxProps: (record) => ({
            disabled: record.exported,
          }),
          selectedRowKeys: selectedBills,
          type: "checkbox",
        }}
      />
    </Card>
  );
}
