import {EditFilled} from "@ant-design/icons";
import {Button, Card, Space, Table} from "antd";
import Dinero from "dinero.js";
import React, {useMemo, useState} from "react";
import {useTranslation} from "react-i18next";
import {connect} from "react-redux";
import {createStructuredSelector} from "reselect";
import {selectJobReadOnly} from "../../redux/application/application.selectors";
import {openChatByPhone, setMessage,} from "../../redux/messaging/messaging.actions";
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 {TemplateList} from "../../utils/TemplateConstants";
import {alphaSort, dateSort} from "../../utils/sorters";
import DataLabel from "../data-label/data-label.component";
import PaymentExpandedRowComponent from "../payment-expanded-row/payment-expanded-row.component";
import PaymentsGenerateLink from "../payments-generate-link/payments-generate-link.component";
import PrintWrapperComponent from "../print-wrapper/print-wrapper.component";
import {useSplitTreatments} from "@splitsoftware/splitio-react";

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

const mapDispatchToProps = (dispatch) => ({
    setPaymentContext: (context) =>
        dispatch(setModalContext({context: context, modal: "payment"})),
    setCardPaymentContext: (context) =>
        dispatch(setModalContext({context: context, modal: "cardPayment"})),
    openChatByPhone: (phone) => dispatch(openChatByPhone(phone)),
    setMessage: (text) => dispatch(setMessage(text)),
});

export function JobPayments({
                                job,
                                jobRO,
                                bodyshop,
                                setMessage,
                                openChatByPhone,
                                setPaymentContext,
                                setCardPaymentContext,
                                refetch
                            }) {

    const {treatments: {ImEXPay}} = useSplitTreatments({
        attributes: {},
        names: ["ImEXPay"],
        splitKey: bodyshop && bodyshop.imexshopid,
    });

    const {t} = useTranslation();
    const [state, setState] = useState({
        sortedInfo: {},
        filteredInfo: {},
    });

    const columns = [
        {
            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("payments.fields.payer"),
            dataIndex: "payer",
            key: "payer",
            sorter: (a, b) => alphaSort(a.payer, b.payer),
            sortOrder:
                state.sortedInfo.columnKey === "payer" && state.sortedInfo.order,
        },
        {
            title: t("payments.fields.amount"),
            dataIndex: "amount",
            key: "amount",
            sorter: (a, b) => a.amount - b.amount,
            sortOrder:
                state.sortedInfo.columnKey === "amount" && state.sortedInfo.order,
            render: (text, record) => (
                <CurrencyFormatter>{record.amount}</CurrencyFormatter>
            ),
        },
        {
            title: t("payments.fields.memo"),
            dataIndex: "memo",
            key: "memo",
            sorter: (a, b) => alphaSort(a.memo, b.memo),
            sortOrder:
                state.sortedInfo.columnKey === "memo" && state.sortedInfo.order,
        },
        {
            title: t("payments.fields.type"),
            dataIndex: "type",
            key: "type",
            sorter: (a, b) => alphaSort(a.type, b.type),
            sortOrder:
                state.sortedInfo.columnKey === "type" && state.sortedInfo.order,
        },
        {
            title: t("payments.fields.transactionid"),
            dataIndex: "transactionid",
            key: "transactionid",
            sorter: (a, b) => alphaSort(a.transactionid, b.transactionid),
            sortOrder:
                state.sortedInfo.columnKey === "transactionid" &&
                state.sortedInfo.order,
        },
        {
            title: t("general.labels.actions"),
            dataIndex: "actions",
            key: "actions",
            render: (text, record) => (
                <Space wrap>
                    <Button
                        // disabled={record.exportedat}
                        onClick={() => {
                            setPaymentContext({
                                actions: {refetch: refetch},
                                context: record,
                            });
                        }}
                    >
                        <EditFilled/>
                    </Button>
                    <PrintWrapperComponent
                        templateObject={{
                            name: TemplateList("payment").payment_receipt.key,
                            variables: {id: record.id},
                        }}
                        messageObject={{
                            to: job.ownr_ea,
                        }}
                        id={job.id}
                    />
                </Space>
            ),
        },
    ];

    const total = useMemo(() => {
        return (
            job.payments &&
            job.payments.reduce((acc, val) => {
                acc = acc.add(Dinero({amount: Math.round(val.amount * 100)}));
                return acc;
            }, Dinero())
        );
    }, [job.payments]);

    const balance = useMemo(() => {
        if (job && job.job_totals && job.job_totals.totals.total_repairs)
            return Dinero(job.job_totals.totals.total_repairs).subtract(total);
        return Dinero({amount: 0}).subtract(total);
    }, [job, total]);

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

    return (
        <Card
            title={t("payments.labels.title")}
            extra={
                <Space wrap>
                    {ImEXPay.treatment === "on" && (
                        <>
                            <Button
                                onClick={() =>
                                    setCardPaymentContext({
                                        actions: {refetch},
                                        context: {jobid: job.id, balance},
                                    })
                                }
                            >
                                {t("menus.header.entercardpayment")}
                            </Button>
                            <PaymentsGenerateLink job={job}/>
                        </>
                    )}
                    <Button
                        disabled={!job.converted}
                        onClick={() =>
                            setPaymentContext({
                                actions: {refetch: refetch},
                                context: {jobid: job.id},
                            })
                        }
                    >
                        {t("menus.header.enterpayment")}
                    </Button>

                    <DataLabel
                        valueStyle={{color: balance.getAmount() !== 0 ? "red" : "green"}}
                        label={t("payments.labels.balance")}
                    >
                        {balance.toFormat()}
                    </DataLabel>
                </Space>
            }
        >
            <Table
                columns={columns}
                rowKey="id"
                pagination={false}
                onChange={handleTableChange}
                dataSource={job && job.payments}
                scroll={{
                    x: true,
                }}
                expandable={{
                    expandedRowRender: (record) => (
                        <PaymentExpandedRowComponent record={record} bodyshop={bodyshop}/>
                    ),
                }}
                summary={() => (
                    <>
                        <Table.Summary.Row>
                            <Table.Summary.Cell>
                                <strong>{t("payments.labels.totalpayments")}</strong>
                            </Table.Summary.Cell>
                            <Table.Summary.Cell/>
                            <Table.Summary.Cell>
                                <strong>{total.toFormat()}</strong>
                            </Table.Summary.Cell>
                            <Table.Summary.Cell/>
                            <Table.Summary.Cell/>
                            <Table.Summary.Cell/>
                        </Table.Summary.Row>
                    </>
                )}
            />
        </Card>
    );
}

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