import { EditFilled, SyncOutlined } from "@ant-design/icons";
import { Button, Card, Input, Space, Table, Typography } from "antd";
import queryString from "query-string";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link, useHistory, useLocation } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { setModalContext } from "../../redux/modals/modals.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { DateFormatter, DateTimeFormatter } from "../../utils/DateFormatter";
import { alphaSort } from "../../utils/sorters";
import { TemplateList } from "../../utils/TemplateConstants";
import CaBcEtfTableModalContainer from "../ca-bc-etf-table-modal/ca-bc-etf-table-modal.container";
import PrintWrapperComponent from "../print-wrapper/print-wrapper.component";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";

const stripeTestEnv = process.env.REACT_APP_STRIPE_PUBLIC_KEY; //.includes("test");

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  setPaymentContext: (context) =>
    dispatch(setModalContext({ context: context, modal: "payment" })),
  setCaBcEtfTableContext: (context) =>
    dispatch(
      setModalContext({ context: context, modal: "ca_bc_eftTableConvert" })
    ),
});

export function PaymentsListPaginated({
  setPaymentContext,
  setCaBcEtfTableContext,
  refetch,
  loading,
  payments,
  total,
  bodyshop,
}) {
  const search = queryString.parse(useLocation().search);
  const { page, sortcolumn, sortorder } = search;
  const history = useHistory();
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" },
  });
  const Templates = TemplateList("payment");
  const { t } = useTranslation();
  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: sortcolumn === "ro_number" && sortorder,
      render: (text, record) => (
        <Link to={"/manage/jobs/" + record.job.id}>
          {record.job.ro_number || t("general.labels.na")}
        </Link>
      ),
    },
    {
      title: t("payments.fields.paymentnum"),
      dataIndex: "paymentnum",
      key: "paymentnum",
      sorter: (a, b) => alphaSort(a.paymentnum, b.paymentnum),
      sortOrder: sortcolumn === "paymentnum" && sortorder,
    },
    {
      title: t("jobs.fields.owner"),
      dataIndex: "owner",
      key: "owner",
      ellipsis: true,
      sorter: (a, b) => alphaSort(a.job.ownr_ln, b.job.ownr_ln),
      sortOrder: sortcolumn === "owner" && sortorder,
      render: (text, record) => {
        return record.job.owner ? (
          <Link to={"/manage/owners/" + record.job.owner.id}>
            <OwnerNameDisplay ownerObject={record} />
          </Link>
        ) : (
          <span>
            <OwnerNameDisplay ownerObject={record} />
          </span>
        );
      },
    },
    {
      title: t("payments.fields.date"),
      dataIndex: "date",
      key: "date",
      sorter: (a, b) => alphaSort(a.date, b.date),
      sortOrder:
        state.sortedInfo.columnKey === "date" && state.sortedInfo.order,
      render: (text, record) => <DateFormatter>{record.date}</DateFormatter>,
    },
    {
      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.payer"),
      dataIndex: "payer",
      key: "payer",
    },
    {
      title: t("payments.fields.type"),
      dataIndex: "type",
      key: "type",
    },
    {
      title: t("payments.fields.transactionid"),
      dataIndex: "transactionid",
      key: "transactionid",
    },
    {
      title: t("payments.fields.stripeid"),
      dataIndex: "stripeid",
      key: "stripeid",
      render: (text, record) =>
        record.stripeid ? (
          <a
            href={
              stripeTestEnv
                ? `https://dashboard.stripe.com/${bodyshop.stripe_acct_id}/test/payments/${record.stripeid}`
                : `https://dashboard.stripe.com/${bodyshop.stripe_acct_id}/payments/${record.stripeid}`
            }
          >
            {record.stripeid}
          </a>
        ) : null,
    },
    {
      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",
      render: (text, record) => (
        <Space>
          <Button
            disabled={record.exportedat}
            onClick={() => {
              setPaymentContext({
                actions: { refetch: refetch },
                context: record,
              });
            }}
          >
            <EditFilled />
          </Button>
          <PrintWrapperComponent
            templateObject={{
              name: Templates.payment_receipt.key,
              variables: { id: record.id },
            }}
            messageObject={{ subject: Templates.payment_receipt.subject }}
            id={record.job && record.job.id}
          />
        </Space>
      ),
    },
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
    search.page = pagination.current;
    search.sortcolumn = sorter.columnKey;
    search.sortorder = sorter.order;
    history.push({ search: queryString.stringify(search) });
  };

  return (
    <Card
      extra={
        <Space wrap>
          {search.search && (
            <>
              <Typography.Title level={4}>
                {t("general.labels.searchresults", { search: search.search })}
              </Typography.Title>
              <Button
                onClick={() => {
                  delete search.search;
                  history.push({ search: queryString.stringify(search) });
                }}
              >
                {t("general.actions.clear")}
              </Button>
            </>
          )}
          {bodyshop.region_config === "CA_BC" && (
            <>
              <CaBcEtfTableModalContainer />
              <Button onClick={() => setCaBcEtfTableContext()}>
                {t("payments.labels.ca_bc_etf_table")}
              </Button>
            </>
          )}
          <Button onClick={() => refetch()}>
            <SyncOutlined />
          </Button>
          <Input.Search
            placeholder={search.search || t("general.labels.search")}
            onSearch={(value) => {
              search.search = value;
              history.push({ search: queryString.stringify(search) });
            }}
            enterButton
          />
        </Space>
      }
    >
      <Table
        loading={loading}
        scroll={{ x: true }}
        pagination={{
          position: "top",
          pageSize: 25,
          current: parseInt(page || 1),
          total: total,
        }}
        columns={columns}
        rowKey="id"
        dataSource={payments}
        onChange={handleTableChange}
      />
    </Card>
  );
}

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