import { EditFilled, SyncOutlined } from "@ant-design/icons";
import { Button, Card, Checkbox, Input, Space } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FaTasks } from "react-icons/fa";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { selectJobReadOnly } from "../../redux/application/application.selectors";
import { setModalContext } from "../../redux/modals/modals.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { DateFormatter } from "../../utils/DateFormatter";
import { alphaSort, dateSort } from "../../utils/sorters";
import { TemplateList } from "../../utils/TemplateConstants";
import BillDeleteButton from "../bill-delete-button/bill-delete-button.component";
import BillDetailEditReturnComponent from "../bill-detail-edit/bill-detail-edit-return.component";
import { HasFeatureAccess } from "../feature-wrapper/feature-wrapper.component";
import LockerWrapperComponent from "../lock-wrapper/lock-wrapper.component";
import PrintWrapperComponent from "../print-wrapper/print-wrapper.component";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import UpsellComponent, { upsellEnum } from "../upsell/upsell.component";

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

const mapDispatchToProps = (dispatch) => ({
  setBillEnterContext: (context) =>
    dispatch(
      setModalContext({
        context: context,
        modal: "billEnter"
      })
    ),
  setReconciliationContext: (context) =>
    dispatch(
      setModalContext({
        context: context,
        modal: "reconciliation"
      })
    ),
  setTaskUpsertContext: (context) => dispatch(setModalContext({ context, modal: "taskUpsert" }))
});

export function BillsListTableComponent({
  bodyshop,
  jobRO,
  job,
  billsQuery,
  handleOnRowClick,
  setBillEnterContext,
  setReconciliationContext,
  setTaskUpsertContext
}) {
  const { t } = useTranslation();

  const [state, setState] = useState({
    sortedInfo: {}
  });
  // const search = queryString.parse(useLocation().search);
  // const selectedBill = search.billid;
  const [searchText, setSearchText] = useState("");

  const Templates = TemplateList("bill");
  const bills = billsQuery.data ? billsQuery.data.bills : [];
  const { refetch } = billsQuery;

  const recordActions = (record, showView = false) => (
    <Space wrap>
      {showView && (
        <Button onClick={() => handleOnRowClick(record)}>
          <EditFilled />
        </Button>
      )}
      <Button
        title={t("tasks.buttons.create")}
        onClick={() => {
          logImEXEvent("bills_create_task", {});
          setTaskUpsertContext({
            context: {
              jobid: job.id,
              billid: record.id
            }
          });
        }}
        icon={<FaTasks />}
      />

      <BillDeleteButton bill={record} jobid={job.id} />
      <BillDetailEditReturnComponent
        data={{ bills_by_pk: { ...record, jobid: job.id, job: job } }}
        disabled={record.is_credit_memo || record.vendorid === bodyshop.inhousevendorid || jobRO}
      />
      {record.isinhouse && (
        <PrintWrapperComponent
          templateObject={{
            name: Templates.inhouse_invoice.key,
            variables: { id: record.id }
          }}
          messageObject={{ subject: Templates.inhouse_invoice.subject }}
        />
      )}
    </Space>
  );
  const columns = [
    {
      title: t("bills.fields.vendorname"),
      dataIndex: "vendorname",
      key: "vendorname",
      sorter: (a, b) => alphaSort(a.vendor.name, b.vendor.name),
      sortOrder: state.sortedInfo.columnKey === "vendorname" && state.sortedInfo.order,
      filters: bills
        ? [...new Set(bills.map((bill) => bill.vendor.name))].map((name) => ({
            text: name,
            value: name
          }))
        : [],
      onFilter: (value, record) => record.vendor.name === value,
      render: (text, record) => <span>{record.vendor.name}</span>
    },
    {
      title: t("bills.fields.invoice_number"),
      dataIndex: "invoice_number",
      key: "invoice_number",
      sorter: (a, b) => alphaSort(a.invoice_number, b.invoice_number),
      sortOrder: state.sortedInfo.columnKey === "invoice_number" && state.sortedInfo.order
    },
    {
      title: t("bills.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("bills.fields.total"),
      dataIndex: "total",
      key: "total",
      sorter: (a, b) => a.total - b.total,
      sortOrder: state.sortedInfo.columnKey === "total" && state.sortedInfo.order,
      render: (text, record) => <CurrencyFormatter>{record.total}</CurrencyFormatter>
    },
    {
      title: t("bills.fields.is_credit_memo"),
      dataIndex: "is_credit_memo",
      key: "is_credit_memo",
      sorter: (a, b) => a.is_credit_memo - b.is_credit_memo,
      sortOrder: state.sortedInfo.columnKey === "is_credit_memo" && state.sortedInfo.order,
      render: (text, record) => <Checkbox checked={record.is_credit_memo} />
    },
    {
      title: t("bills.fields.exported"),
      dataIndex: "exported",
      key: "exported",
      sorter: (a, b) => a.exported - b.exported,
      sortOrder: state.sortedInfo.columnKey === "exported" && state.sortedInfo.order,
      render: (text, record) => <Checkbox checked={record.exported} />
    },
    {
      title: t("general.labels.actions"),
      dataIndex: "actions",
      key: "actions",
      render: (text, record) => recordActions(record, true)
    }
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
    logImEXEvent("bills_list_sort_filter", { pagination, filters, sorter });
  };

  const filteredBills = bills
    ? searchText === ""
      ? bills
      : bills.filter(
          (b) =>
            (b.invoice_number || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (b.vendor.name || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (b.total || "").toString().toLowerCase().includes(searchText.toLowerCase())
        )
    : [];

  const hasBillsAccess = HasFeatureAccess({ bodyshop, featureName: "bills" });

  return (
    <Card
      title={t("bills.labels.bills")}
      extra={
        <Space wrap>
          <Button onClick={() => refetch()} icon={<SyncOutlined />} />
          {job && job.converted ? (
            <>
              <Button
                disabled={!hasBillsAccess}
                onClick={() => {
                  setBillEnterContext({
                    actions: { refetch: billsQuery.refetch },
                    context: {
                      job
                    }
                  });
                }}
              >
                <LockerWrapperComponent featureName="bills">{t("jobs.actions.postbills")}</LockerWrapperComponent>
              </Button>
              <Button
                disabled={!hasBillsAccess}
                onClick={() => {
                  logImEXEvent("bills_reconcile", {});
                  setReconciliationContext({
                    actions: { refetch: billsQuery.refetch },
                    context: {
                      job,
                      bills: (billsQuery.data && billsQuery.data.bills) || []
                    }
                  });
                }}
                id="reconcile-bills-button"
              >
                <LockerWrapperComponent featureName="bills"> {t("jobs.actions.reconcile")}</LockerWrapperComponent>
              </Button>
            </>
          ) : null}

          <Input.Search
            placeholder={t("general.labels.search")}
            value={searchText}
            disabled={!hasBillsAccess}
            onChange={(e) => {
              e.preventDefault();
              setSearchText(e.target.value);
            }}
            enterButton
          />
        </Space>
      }
    >
      <ResponsiveTable
        loading={billsQuery.loading}
        scroll={{
          x: true // y: "50rem"
        }}
        columns={columns}
        mobileColumnKeys={["vendorname", "invoice_number", "date", "total", "actions"]}
        rowKey="id"
        dataSource={hasBillsAccess ? filteredBills : []}
        onChange={handleTableChange}
        locale={{
          ...(!hasBillsAccess && {
            emptyText: <UpsellComponent upsell={upsellEnum().bills.general} />
          })
        }}
      />
    </Card>
  );
}

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