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

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

const mapDispatchToProps = () => ({
  //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] = useLocalStorage("accounting-payables-table-state", {
    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",

      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
            enterButton
          />
        </Space>
      }
    >
      <ResponsiveTable
        loading={loading}
        dataSource={dataSource}
        pagination={{ placement: "top", pageSize: exportPageLimit, showSizeChanger: false }}
        columns={columns}
        mobileColumnKeys={["vendorname", "invoice_number", "ro_number", "total", "actions"]}
        rowKey="id"
        onChange={handleTableChange}
        rowSelection={{
          onSelectAll: (selected, selectedRows) => setSelectedBills(selectedRows.map((i) => i.id)),
          onSelect: (record, selected, selectedRows) => {
            setSelectedBills(selectedRows.map((i) => i.id));
          },
          getCheckboxProps: (record) => ({
            disabled: record.exported
          }),
          selectedRowKeys: selectedBills,
          type: "checkbox"
        }}
      />
    </Card>
  );
}
