import { EditFilled, SyncOutlined } from "@ant-design/icons";
import { useApolloClient } from "@apollo/client/react";
import { Button, Card, Input, Space, Typography } from "antd";
import axios from "axios";
import queryString from "query-string";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { QUERY_PAYMENT_BY_ID } from "../../graphql/payments.queries";
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 { TemplateList } from "../../utils/TemplateConstants";
import { pageLimit } from "../../utils/config";
import { alphaSort } from "../../utils/sorters";
import CaBcEtfTableModalContainer from "../ca-bc-etf-table-modal/ca-bc-etf-table-modal.container";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";
import PrintWrapperComponent from "../print-wrapper/print-wrapper.component";
import ResponsiveTable from "../responsive-table/responsive-table.component";

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 [openSearchResults, setOpenSearchResults] = useState([]);
  const [searchLoading, setSearchLoading] = useState(false);
  const { page, sortcolumn, sortorder } = search;
  const client = useApolloClient();
  const history = useNavigate();
  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) => {
        return record.job ? (
          <Link to={"/manage/jobs/" + record.job.id}>{record.job.ro_number || t("general.labels.na")}</Link>
        ) : (
          <span>{t("general.labels.na")}</span>
        );
      }
    },
    {
      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.job} />
          </Link>
        ) : (
          <span>
            <OwnerNameDisplay ownerObject={record.job} />
          </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.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
            icon={<EditFilled />}
            // disabled={record.exportedat}
            onClick={async () => {
              let apolloResults;
              if (search.search) {
                const { data } = await client.query({
                  query: QUERY_PAYMENT_BY_ID,
                  variables: {
                    paymentId: record.id
                  }
                });
                apolloResults = data.payments_by_pk;
              }
              setPaymentContext({
                actions: {
                  refetch: apolloResults
                    ? (updatedRecord) => {
                        setOpenSearchResults((results) =>
                          results.map((result) => {
                            if (result.id !== record.id) {
                              return result;
                            }
                            return updatedRecord;
                          })
                        );
                      }
                    : refetch
                },
                context: { ...(apolloResults ? apolloResults : record), refetchRequiresContext: true }
              });
            }}
          />
          <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({ search: queryString.stringify(search) });
  };

  useEffect(() => {
    if (search.search && search.search.trim() !== "") {
      searchPayments();
    }
  }, []);

  async function searchPayments(value) {
    try {
      setSearchLoading(true);
      const searchData = await axios.post("/search", {
        search: value || search.search,
        index: "payments"
      });
      setOpenSearchResults(searchData.data.hits.hits.map((s) => s._source));
    } catch (error) {
      console.log("Error while fetching search results", error);
    } finally {
      setSearchLoading(false);
    }
  }

  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;
                  delete search.page;
                  history({ 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()} icon={<SyncOutlined />} />
          <Input.Search
            placeholder={search.search || t("general.labels.search")}
            onSearch={(value) => {
              search.search = value;
              history({ search: queryString.stringify(search) });
              searchPayments(value);
            }}
            loading={loading || searchLoading}
            enterButton
          />
        </Space>
      }
    >
      <ResponsiveTable
        loading={loading || searchLoading}
        scroll={{ x: true }}
        pagination={
          search?.search
            ? {
                pageSize: pageLimit,
                showSizeChanger: false
              }
            : {
                pageSize: pageLimit,
                current: parseInt(page || 1),
                total: total,
                showSizeChanger: false
              }
        }
        columns={columns}
        mobileColumnKeys={["ro_number", "owner", "date", "amount", "actions"]}
        rowKey="id"
        dataSource={search?.search ? openSearchResults : payments}
        onChange={handleTableChange}
      />
    </Card>
  );
}

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