import { Card, Input, Space, Table } from "antd";
import React, { 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, DateTimeFormatter } from "../../utils/DateFormatter";
import { pageLimit } from "../../utils/config";
import { alphaSort, dateSort } from "../../utils/sorters";
import ExportLogsCountDisplay from "../export-logs-count-display/export-logs-count-display.component";
import OwnerNameDisplay, {
  OwnerNameDisplayFunction,
} from "../owner-name-display/owner-name-display.component";
import PaymentExportButton from "../payment-export-button/payment-export-button.component";
import PaymentMarkSelectedExported from "../payment-mark-selected-exported/payment-mark-selected-exported.component";
import PaymentsExportAllButton from "../payments-export-all-button/payments-export-all-button.component";
import QboAuthorizeComponent from "../qbo-authorize/qbo-authorize.component";

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

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

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

export function AccountingPayablesTableComponent({
  bodyshop,
  loading,
  payments,
  refetch,
}) {
  const { t } = useTranslation();
  const [selectedPayments, setSelectedPayments] = 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("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("payments.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("jobs.fields.owner"),
      dataIndex: "owner",
      key: "owner",
      ellipsis: true,
      sorter: (a, b) =>
        alphaSort(
          OwnerNameDisplayFunction(a.job),
          OwnerNameDisplayFunction(b.job)
        ),
      sortOrder:
        state.sortedInfo.columnKey === "owner" && state.sortedInfo.order,
      render: (text, record) => {
        return record.job.owner ? (
          <Link to={"/manage/owners/" + record.job.owner.id}>
            <OwnerNameDisplay ownerObject={record.job} />
          </Link>
        ) : (
          <span>
            <OwnerNameDisplay ownerObject={record.job} />
          </span>
        );
      },
    },
    {
      title: t("payments.fields.amount"),
      dataIndex: "amount",
      key: "amount",
      sorter: (a, b) => a.amount - b.amount,
      sortOrder:
        state.sortedInfo.columnKey === "amount" && state.sortedInfo.order,
      render: (text, record) => (
        <CurrencyFormatter>{record.amount}</CurrencyFormatter>
      ),
    },
    {
      title: t("payments.fields.memo"),
      dataIndex: "memo",
      key: "memo",
    },
    {
      title: t("payments.fields.transactionid"),
      dataIndex: "transactionid",
      key: "transactionid",
    },
    {
      title: t("payments.fields.created_at"),
      dataIndex: "created_at",
      key: "created_at",
      sorter: (a, b) => dateSort(a.created_at, b.created_at),
      sortOrder:
        state.sortedInfo.columnKey === "created_at" && state.sortedInfo.order,
      render: (text, record) => (
        <DateTimeFormatter>{record.created_at}</DateTimeFormatter>
      ),
    },
    // {
    //   title: t("payments.fields.exportedat"),
    //   dataIndex: "exportedat",
    //   key: "exportedat",
    //   render: (text, record) => (
    //     <DateTimeFormatter>{record.exportedat}</DateTimeFormatter>
    //   ),
    // },
    {
      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) => (
        <PaymentExportButton
          paymentId={record.id}
          disabled={transInProgress || !!record.exportedat}
          loadingCallback={setTransInProgress}
          setSelectedPayments={setSelectedPayments}
          refetch={refetch}
        />
      ),
    },
  ];

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

  const dataSource = state.search
    ? payments.filter(
        (v) =>
          (v.paymentnum || "")
            .toLowerCase()
            .includes(state.search.toLowerCase()) ||
          ((v.job && v.job.ro_number) || "")
            .toLowerCase()
            .includes(state.search.toLowerCase()) ||
          ((v.job && v.job.ownr_fn) || "")
            .toLowerCase()
            .includes(state.search.toLowerCase()) ||
          ((v.job && v.job.ownr_ln) || "")
            .toLowerCase()
            .includes(state.search.toLowerCase()) ||
          ((v.job && v.job.ownr_co_nm) || "")
            .toLowerCase()
            .includes(state.search.toLowerCase())
      )
    : payments;

  return (
    <Card
      extra={
        <Space wrap>
          <PaymentMarkSelectedExported
            paymentIds={selectedPayments}
            disabled={transInProgress || selectedPayments.length === 0}
            loadingCallback={setTransInProgress}
            completedCallback={setSelectedPayments}
            refetch={refetch}
          />
          <PaymentsExportAllButton
            paymentIds={selectedPayments}
            disabled={transInProgress || selectedPayments.length === 0}
            loadingCallback={setTransInProgress}
            completedCallback={setSelectedPayments}
            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) =>
            setSelectedPayments(selectedRows.map((i) => i.id)),
          onSelect: (record, selected, selectedRows, nativeEvent) => {
            setSelectedPayments(selectedRows.map((i) => i.id));
          },
          getCheckboxProps: (record) => ({
            disabled: record.exported,
          }),
          selectedRowKeys: selectedPayments,
          type: "checkbox",
        }}
      />
    </Card>
  );
}
