import { SyncOutlined } from "@ant-design/icons";
import { useQuery } from "@apollo/client";
import { Button, Card, Checkbox, Input, Space, Table, Typography } from "antd";
import _ from "lodash";
import queryString from "query-string";
import React 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 AlertComponent from "../../components/alert/alert.component";
import { QUERY_EXPORT_LOG_PAGINATED } from "../../graphql/accounting.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { DateTimeFormatter } from "../../utils/DateFormatter";

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

export function ExportLogsPageComponent({ bodyshop }) {
  const searchParams = queryString.parse(useLocation().search);
  const { page, sortcolumn, sortorder, search } = searchParams;
  const history = useHistory();

  const { loading, error, data, refetch } = useQuery(
    QUERY_EXPORT_LOG_PAGINATED,
    {
      fetchPolicy: "network-only",
      nextFetchPolicy: "network-only",
      variables: {
        search: search || "",
        offset: page ? (page - 1) * 25 : 0,
        limit: 25,
        order: [
          {
            [sortcolumn || "created_at"]: sortorder
              ? sortorder === "descend"
                ? "desc"
                : "asc"
              : "desc",
          },
        ],
      },
    }
  );

  const { t } = useTranslation();

  if (error) return <AlertComponent message={error.message} type="error" />;

  const handleTableChange = (pagination, filters, sorter) => {
    searchParams.page = pagination.current;
    searchParams.sortcolumn = sorter.columnKey;
    searchParams.sortorder = sorter.order;
    if (filters.status) {
      searchParams.statusFilters = JSON.stringify(
        _.flattenDeep(filters.status)
      );
    } else {
      delete searchParams.statusFilters;
    }
    history.push({ search: queryString.stringify(searchParams) });
  };

  const columns = [
    {
      title: t("general.labels.created_at"),
      dataIndex: "created_at",
      key: "created_at",
      render: (text, record) => (
        <DateTimeFormatter>{record.created_at}</DateTimeFormatter>
      ),
    },
    {
      title: t("employees.fields.user_email"),
      dataIndex: "useremail",
      key: "useremail",
    },
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "ro_number",
      key: "ro_number",

      render: (text, record) =>
        record.job && (
          <Link to={`/manage/jobs/${record.job.id}`}>
            {(record.job && record.job.ro_number) || t("general.labels.na")}
          </Link>
        ),
    },
    {
      title: t("bills.fields.invoice_number"),
      dataIndex: "invoice_number",
      key: "invoice_number",
      render: (text, record) =>
        record.bill && (
          <Link to={"/manage/bills?billid=" + (record.bill && record.bill.id)}>
            {record.bill && record.bill.invoice_number}
          </Link>
        ),
    },
    {
      title: t("payments.fields.paymentnum"),
      dataIndex: "paymentnum",
      key: "paymentnum",
      render: (text, record) =>
        record.payment && (
          <Link
            to={
              "/manage/payments?search=" +
              (record.payment && record.payment.paymentnum)
            }
          >
            {record.payment && record.payment.paymentnum}
          </Link>
        ),
    },
    {
      title: t("general.labels.successful"),
      dataIndex: "successful",
      key: "successful",
      render: (text, record) => (
        <Checkbox disabled checked={record.successful} />
      ),
    },
    {
      title: t("general.labels.message"),
      dataIndex: "message",
      key: "message",
      render: (text, record) =>
        record.message && (
          <div>
            <ul>
              {JSON.parse(record.message).map((m, idx) => (
                <li key={idx}>{m}</li>
              ))}
            </ul>
          </div>
        ),
    },
  ];

  return (
    <Card
      extra={
        <Space wrap>
          {searchParams.search && (
            <>
              <Typography.Title level={4}>
                {t("general.labels.searchresults", {
                  search: searchParams.search,
                })}
              </Typography.Title>
              <Button
                onClick={() => {
                  delete searchParams.search;
                  history.push({ search: queryString.stringify(searchParams) });
                }}
              >
                {t("general.actions.clear")}
              </Button>
            </>
          )}
          <Button onClick={() => refetch()}>
            <SyncOutlined />
          </Button>
          <Input.Search
            placeholder={searchParams.search || t("general.labels.search")}
            onSearch={(value) => {
              searchParams.search = value;
              history.push({ search: queryString.stringify(searchParams) });
            }}
          />
        </Space>
      }
    >
      <Table
        loading={loading}
        pagination={{
          position: "top",
          pageSize: 25,
          current: parseInt(page || 1),
          total: data && data.search_exportlog_aggregate.aggregate.count,
        }}
        columns={columns}
        rowKey="id"
        dataSource={data && data.search_exportlog}
        style={{ height: "100%" }}
        scroll={{ x: true }}
        onChange={handleTableChange}
      />
    </Card>
  );
}

export default connect(mapStateToProps, null)(ExportLogsPageComponent);
