import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { DateTime } from 'luxon';
import { FluentCardText } from '../surfaces/cards/fluentCards/FluentCardText';
import { IndicatorChip } from '../utilityDisplay/IndicatorChip';
import { makeStyles, Divider, FormControlLabel } from '@material-ui/core';
import { Box } from '../Box';
import { AmbientCard } from '../surfaces/cards/AmbientCard';
import { Typography } from '../dataDisplay/typography/Typography';
import { Grid } from '../Grid';
import { ListElement } from '../mapLayout/ui/ListCard';
import { useTranslation } from 'react-i18next';
import { FluentCheckbox } from '../inputs/checkbox/FluentCheckbox';
import { FormControl } from '../utilityDisplay/FormControl';
import { Field } from '../../utilities/form/Field';
import { FluentTextField } from '../inputs/textField/FluentTextField';
import { Form } from '../../utilities/form/Form';
import { apiMutate } from '../../utilities/useAxiosMutate';
import { LinearProgress } from '../loading/LinearProgress';
import { ConfigService } from '../../configService';
const useStyles = makeStyles((theme) => ({
    formControlHalf: {
        width: '40%'
    },
    formControl: {
        width: '100%'
    },
    formControlMargin: {
        width: '100%',
        marginTop: '5px'
    },
    formControlCheck: {
        width: '100%',
        marginTop: '5px',
        marginLeft: '3px'
    },
    submitControl: {
        marginTop: '35px'
    },
    assetTypeLabel: {
        top: theme.spacing(-0.7)
    },
    labelText: {
        color: 'rgba(0, 0, 0)',
        fontSize: '0.875rem'
    },
    main: {
        flexGrow: 1,
        padding: '0 24px',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    appIcon: {
        width: 24,
        height: 24,
        color: theme.palette.text.primary
    },
    arrowIcon: {
        width: 12,
        height: 12
    },
    linkTitle: {
        marginRight: theme.spacing(1)
    },
    formControlGeneral: {
        width: '100%',
        marginLeft: '5px',
        marginTop: '5px'
    },
    cardNumber: {
        width: '60%'
    },
    accordion: {
        width: '100%',
        margin: '0px',
        padding: '0px',
        boxShadow: 'none',
        backgroundColor: 'inherit',
        '&:before': {
            display: 'none'
        },
        '&$expanded': {
            margin: '0px'
        }
    },
    accordionSummary: {
        padding: '0px',
        paddingLeft: '5px',
        margin: '0px',
        minHeight: '0px',
        backgroundColor: 'inherit',
        flexDirection: 'row-reverse',
        '&$expanded': {
            margin: '0px',
            padding: '0px',
            minHeight: '0px'
        }
    },
    expanded: {
        margin: '0px',
        paddingLeft: '5px'
    },
    content: {
        margin: 0,
        backgroundColor: 'inherit',
        '&$expanded': {
            margin: 0
        }
    },
    accordionDetails: {
        padding: '0px',
        display: 'block',
        margin: '0px'
    },
    cardContent: {
        backgroundColor: '#FAFAFA'
    },
    listItem: {
        paddingTop: '3px',
        paddingBottom: '3px',
        fontSize: '0.875rem'
    },
    listItemDetail: {
        display: 'flex',
        justifyContent: 'flex-end'
    },
    listItemAccordion: {
        paddingTop: '3px',
        paddingBottom: '3px',
        paddingLeft: '0px'
    },
    divider: {
        margin: '0px 12px'
    },
    dividerBold: {
        margin: '0px 12px',
        backgroundColor: 'black'
    },
    itemCheckbox: {
        padding: '0px'
    },
    itemDescription: {
        color: 'grey'
    },
    list: {
        backgroundColor: '#FFF'
    },
    dropdown: {
        marginTop: theme.spacing(-1),
        backgroundColor: '#FFF'
    },
    locationDropDown: {
        margin: theme.spacing(0),
        marginTop: theme.spacing(-0.5),
        fontSize: '0.75rem'
    },
    box: {
        display: 'flex',
        justifyContent: 'space-around',
        flexDirection: 'row',
        paddingBottom: '15px',
        gap: '10px',
        [theme.breakpoints.down('sm')]: {
            flexDirection: 'column',
            flexWrap: 'wrap',
            alignItems: 'flex-start'
        }
    }
}));
const PAYMENT_APPROVED = 1;
const PAYMENT_DENIED = 43;
const RESULT_SUCCESS = 200;
const RESULT_FAILURE = 401;
export const PaymentReversalForm = ({ id, paymentData, onSubmitCompleted }) => {
    var _a;
    const classes = useStyles();
    const { t } = useTranslation();
    const [loading, setLoading] = useState(true);
    const [paymentTransaction, setPaymentTransaction] = useState(undefined);
    /**
     * API call to get the payment transaction details
     */
    const getPaymentTransaction = useCallback(async (payload) => {
        if (!payload) {
            return null;
        }
        return apiMutate(ConfigService.pgV1ApiUrl, `PaymentTransaction/search`, {
            method: 'POST',
            data: payload
        }, {});
    }, []);
    /**
     * API call to get the account information by account number
     */
    const reverseTransactionExecute = useCallback(async (transactionID) => {
        if (!transactionID) {
            return null;
        }
        return apiMutate(ConfigService.pgV1ApiUrl, `PaymentTransaction/${transactionID}`, {
            method: 'DELETE',
        }, {});
    }, []);
    /**
     * submitAccountDetailsForm
     * @param {*} formData
     * @return {*}
     */
    const handleSubmitPaymentReversal = (values) => {
        // const data = {
        //   amountToReverse: values.amountToReverse,
        //   isSendCustomerPaymentConfirmation:
        //     values.isSendCustomerPaymentConfirmation
        // };
        if (!(paymentData === null || paymentData === void 0 ? void 0 : paymentData.transactionId)) {
            return;
        }
        reverseTransactionExecute(paymentData === null || paymentData === void 0 ? void 0 : paymentData.transactionId)
            .then(() => {
            onSubmitCompleted === null || onSubmitCompleted === void 0 ? void 0 : onSubmitCompleted({ transactionId: paymentData === null || paymentData === void 0 ? void 0 : paymentData.transactionId, error: false });
        })
            .catch((error) => {
            onSubmitCompleted === null || onSubmitCompleted === void 0 ? void 0 : onSubmitCompleted({ transactionId: paymentData === null || paymentData === void 0 ? void 0 : paymentData.transactionId, error });
        });
    };
    useEffect(() => {
        const fetchData = async () => {
            var _a, _b;
            try {
                setLoading(true);
                const response = await getPaymentTransaction({
                    eagerLoad: true,
                    pageNumber: 1,
                    pageSize: 20,
                    filterElements: [
                        {
                            searchField: 'transactionId',
                            searchValue: paymentData === null || paymentData === void 0 ? void 0 : paymentData.transactionId,
                            searchOperator: '=',
                        },
                    ],
                    orderElements: [],
                });
                if (response === null || response === void 0 ? void 0 : response.data) {
                    setPaymentTransaction((_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.pageList) === null || _b === void 0 ? void 0 : _b[0]);
                }
            }
            catch (err) {
                console.error(err);
            }
            finally {
                setLoading(false);
            }
        };
        if (paymentData === null || paymentData === void 0 ? void 0 : paymentData.transactionId) {
            fetchData();
        }
    }, [getPaymentTransaction, paymentData]);
    const statusText = useMemo(() => {
        return ((paymentTransaction === null || paymentTransaction === void 0 ? void 0 : paymentTransaction.responseCode) === PAYMENT_APPROVED && (paymentTransaction === null || paymentTransaction === void 0 ? void 0 : paymentTransaction.paymentResultID) === RESULT_SUCCESS) ? 'Approved' :
            ((paymentTransaction === null || paymentTransaction === void 0 ? void 0 : paymentTransaction.responseCode) === PAYMENT_DENIED && (paymentTransaction === null || paymentTransaction === void 0 ? void 0 : paymentTransaction.paymentResultID) === RESULT_FAILURE) ? 'Declined' : 'Undetermined';
    }, [paymentTransaction]);
    const statusCode = useMemo(() => {
        return ((paymentTransaction === null || paymentTransaction === void 0 ? void 0 : paymentTransaction.responseCode) === PAYMENT_APPROVED && (paymentTransaction === null || paymentTransaction === void 0 ? void 0 : paymentTransaction.paymentResultID) === RESULT_SUCCESS) ? 'ok' :
            ((paymentTransaction === null || paymentTransaction === void 0 ? void 0 : paymentTransaction.responseCode) === PAYMENT_DENIED && (paymentTransaction === null || paymentTransaction === void 0 ? void 0 : paymentTransaction.paymentResultID) === RESULT_FAILURE) ? 'error' : 'warning';
    }, [paymentTransaction]);
    return (React.createElement(Box, null, loading && (React.createElement(Box, { sx: { width: '100%' } }, React.createElement(LinearProgress, null))), React.createElement(Box, { className: classes.box }, React.createElement(FluentCardText, { title: "Value", description: `$${paymentData === null || paymentData === void 0 ? void 0 : paymentData.amount}` }), React.createElement(FluentCardText, { title: "Status", description: React.createElement(IndicatorChip, { text: statusText, status: statusCode }) })), React.createElement(AmbientCard, { fullWidth: true }, React.createElement(Typography, { variant: "subtitle2", style: { marginTop: '0px', marginBottom: '10px' } }, t('Payment Details')), React.createElement(Box, { display: "flex", flexDirection: "column" }, React.createElement(Grid, { container: true, spacing: 1 }, [
        [t('Transaction ID'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.transactionId) || t('N/A')],
        [t('Date/Time'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.transactionDate) ? DateTime.fromJSDate(new Date(paymentData === null || paymentData === void 0 ? void 0 : paymentData.transactionDate)).toFormat('EEE, MMM d, yyyy') : t('N/A')],
        [t('Processor'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.paymentSourceName) || t('No Information found')],
        [t('Response Code'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.authorizationNumber) || t('N/A')]
    ].map(([k, v]) => (React.createElement(Grid, { item: true, xs: 12, sm: 6 }, React.createElement(ListElement, { subject: k, value: v, hideDivider: true })))))), React.createElement(Divider, { style: { marginTop: '10px', marginBottom: '10px' } }), React.createElement(Box, { display: "flex", flexDirection: "column" }, React.createElement(Grid, { container: true, spacing: 1 }, [
        [t('Customer Name'), (paymentTransaction === null || paymentTransaction === void 0 ? void 0 : paymentTransaction.reference3) || t('N/A')],
        [t('Type'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.tender) || t('N/A')],
        [t('Card Holder Name'), t('N/A')],
        [t('CC Number'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.cardLast4) || t('N/A')],
        [t('Company'), ((_a = paymentTransaction === null || paymentTransaction === void 0 ? void 0 : paymentTransaction.applicationClient) === null || _a === void 0 ? void 0 : _a.name) || t('N/A')],
        [t('Expiration Date'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.date) || t('N/A')],
        [t('AVS'), t('N/A')],
        [t('Status'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.authorizationNumber) ? 'Approved' : 'Declined'],
        [t('Confirmation'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.authorizationNumber) || t('N/A')]
    ].map(([k, v]) => (React.createElement(Grid, { item: true, xs: 12, sm: 6 }, React.createElement(ListElement, { subject: k, value: v, hideDivider: true })))))), React.createElement(Divider, { style: { marginTop: '10px', marginBottom: '10px' } }), React.createElement(Box, { display: "flex", flexDirection: "column" }, React.createElement(Grid, { container: true, spacing: 1 }, [
        [t('First Attempt Date'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.date) || t('N/A')],
        [t('Initial Transaction'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.date) || t('N/A')],
        [t('Next Attempt Date'), (paymentData === null || paymentData === void 0 ? void 0 : paymentData.date) || t('N/A')],
        [t('Retry Count'), t('N/A')]
    ].map(([k, v]) => (React.createElement(Grid, { item: true, xs: 12, sm: 6 }, React.createElement(ListElement, { subject: k, value: v, hideDivider: true })))))), React.createElement(Divider, { style: { marginTop: '10px', marginBottom: '10px' } }), React.createElement(Form, { id: id, onSubmit: handleSubmitPaymentReversal, render: ({ handleSubmit, form, values }) => {
            return (React.createElement(React.Fragment, null, React.createElement(FormControl, { className: classes.formControl }, React.createElement(Field, { component: FluentTextField, ComponentProps: {
                    label: t('Amount to Reverse'),
                    variant: 'outlined',
                    margin: 'normal',
                    size: 'small',
                    disabled: false,
                    fullWidth: true,
                    autoComplete: 'off',
                    inputProps: {
                        maxLength: 256,
                        autocomplete: 'off'
                    }
                }, name: "amountToReverse", initialValue: paymentData === null || paymentData === void 0 ? void 0 : paymentData.amount, onChange: () => { }, required: true })), React.createElement(FormControl, { className: classes.formControlGeneral }, React.createElement(FormControlLabel, { control: React.createElement(Field, { component: FluentCheckbox, name: "isSendCustomerPaymentConfirmation", type: "checkbox", defaultValue: false, required: false, onChange: () => { }, 
                    // @ts-ignore
                    size: "small" }), label: t('Send Customer Payment Confirmation') }))));
        } }))));
};
//# sourceMappingURL=PaymentReversalForm.js.map