import { Card, Input, Space, Table } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { logImEXEvent } from "../../firebase/firebase.utils";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { DateFormatter, DateTimeFormatter } from "../../utils/DateFormatter";
import { alphaSort, dateSort } from "../../utils/sorters";
import PaymentExportButton from "../payment-export-button/payment-export-button.component";
import PaymentsExportAllButton from "../payments-export-all-button/payments-export-all-button.component";

export default function AccountingPayablesTableComponent({
  loading,
  payments,
}) {
  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(a.job.ownr_ln, b.job.ownr_ln),
      sortOrder:
        state.sortedInfo.columnKey === "owner" && state.sortedInfo.order,
      render: (text, record) => {
        return record.job.owner ? (
          <Link to={"/manage/owners/" + record.job.owner.id}>
            {`${record.job.ownr_fn || ""} ${record.job.ownr_ln || ""} ${
              record.job.ownr_co_nm || ""
            }`}
          </Link>
        ) : (
          <span>{`${record.job.ownr_fn || ""} ${record.job.ownr_ln || ""} ${
            record.job.ownr_co_nm || ""
          }`}</span>
        );
      },
    },
    {
      title: t("payments.fields.amount"),
      dataIndex: "amount",
      key: "amount",
      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.stripeid"),
      dataIndex: "stripeid",
      key: "stripeid",
    },
    {
      title: t("payments.fields.created_at"),
      dataIndex: "created_at",
      key: "created_at",
      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("general.labels.actions"),
      dataIndex: "actions",
      key: "actions",
      sorter: (a, b) => a.clm_total - b.clm_total,

      render: (text, record) => (
        <PaymentExportButton
          paymentId={record.id}
          disabled={transInProgress || !!record.exportedat}
          loadingCallback={setTransInProgress}
        />
      ),
    },
  ];

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

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

  return (
    <Card
      extra={
        <Space wrap>
          <PaymentsExportAllButton
            paymentIds={selectedPayments}
            disabled={transInProgress || selectedPayments.length === 0}
            loadingCallback={setTransInProgress}
            completedCallback={setSelectedPayments}
          />
          <Input
            value={state.search}
            onChange={handleSearch}
            placeholder={t("general.labels.search")}
            allowClear
          />
        </Space>
      }
    >
      <Table
        loading={loading}
        dataSource={dataSource}
        pagination={{ position: "top", pageSize: 50 }}
        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>
  );
}
