/**
 * SeaXPay Payment Gateway - WooCommerce Blocks Integration
 * Reference MetaMask plugin style, supports real-time exchange rate query
 */
const { registerPaymentMethod } = window.wc.wcBlocksRegistry;
const { getSetting } = window.wc.wcSettings;
const { decodeEntities } = window.wp.htmlEntities;
const { createElement, useState, useEffect, useCallback } = window.wp.element;

const settings = getSetting('seaxpay_data', {});
const supportedCoins = settings.supported_coins || {};

const HIGH_FEE_NETWORKS = ['ERC20', 'ETHEREUM', 'ETH'];

const isHighFeeNetwork = function (network) {
    return HIGH_FEE_NETWORKS.indexOf(String(network || '').toUpperCase()) !== -1;
};

const Content = (props) => {
    const { eventRegistration, emitResponse, billing } = props;
    const { onPaymentSetup } = eventRegistration;

    const cartTotal = billing?.cartTotal?.value ? (billing.cartTotal.value / 100) : (settings.cart_total || 0);
    const cartCurrency = billing?.currency?.code || settings.cart_currency || 'USD';

    const getNetworksForCoin = (coin) => {
        if (supportedCoins[coin] && supportedCoins[coin].networks) {
            return supportedCoins[coin].networks;
        }
        return {};
    };

    const isNetworkEligible = (network, networkMeta) => {
        if (!networkMeta) return true;
        const min = networkMeta.min_amount_usd;
        if (min === null || min === undefined || min <= 0) return true;
        if (cartTotal <= 0) return true;
        return cartTotal >= min;
    };

    const sortNetworkKeys = (networks) => {
        return Object.keys(networks).sort((a, b) => {
            const ma = networks[a];
            const mb = networks[b];
            const ea = isNetworkEligible(a, ma) ? 0 : 1;
            const eb = isNetworkEligible(b, mb) ? 0 : 1;
            if (ea !== eb) return ea - eb;
            const ra = ma && ma.recommended ? 0 : 1;
            const rb = mb && mb.recommended ? 0 : 1;
            if (ra !== rb) return ra - rb;
            const ha = isHighFeeNetwork(a) ? 1 : 0;
            const hb = isHighFeeNetwork(b) ? 1 : 0;
            if (ha !== hb) return ha - hb;
            return 0;
        });
    };

    const pickBestNetwork = (networks) => {
        const keys = sortNetworkKeys(networks);
        for (let i = 0; i < keys.length; i++) {
            if (isNetworkEligible(keys[i], networks[keys[i]])) {
                return keys[i];
            }
        }
        return keys.length > 0 ? keys[0] : '';
    };

    const getDefaultCoinAndNetwork = () => {
        const coinKeys = Object.keys(supportedCoins);
        if (coinKeys.length > 0) {
            const firstCoin = coinKeys[0];
            const networks = supportedCoins[firstCoin]?.networks || {};
            return {
                coin: firstCoin,
                network: pickBestNetwork(networks)
            };
        }
        return { coin: 'USDT', network: 'TRC20' };
    };

    const defaultValues = getDefaultCoinAndNetwork();
    const [selectedCoin, setSelectedCoin] = useState(defaultValues.coin);
    const [selectedNetwork, setSelectedNetwork] = useState(defaultValues.network);
    const [cryptoAmount, setCryptoAmount] = useState(0);
    const [exchangeRate, setExchangeRate] = useState(0);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');

    const fetchQuote = useCallback(async (coin, network) => {
        if (!coin || !network || cartTotal <= 0) return;

        setLoading(true);
        setError('');

        try {
            const formData = new FormData();
            formData.append('action', 'seaxpay_get_quote');
            formData.append('nonce', settings.nonce);
            formData.append('coin', coin);
            formData.append('network', network);
            formData.append('fiat_amount', cartTotal);
            formData.append('fiat_currency', cartCurrency);

            const response = await fetch(settings.ajax_url, {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (result.success && result.data) {
                setCryptoAmount(result.data.crypto_amount);
                setExchangeRate(result.data.exchange_rate);
            } else {
                setError(result.data || 'Failed to get quote');
                setCryptoAmount(cartTotal);
                setExchangeRate(0);
            }
        } catch (err) {
            console.error('SeaXPay quote error:', err);
            setError('Network error');
            setCryptoAmount(cartTotal);
        } finally {
            setLoading(false);
        }
    }, [cartTotal, cartCurrency]);

    useEffect(() => {
        const nets = getNetworksForCoin(selectedCoin);
        const current = nets[selectedNetwork];
        if (!current || !isNetworkEligible(selectedNetwork, current)) {
            const best = pickBestNetwork(nets);
            if (best && best !== selectedNetwork) {
                setSelectedNetwork(best);
            }
        }
    }, [cartTotal, selectedCoin, selectedNetwork]);

    useEffect(() => {
        fetchQuote(selectedCoin, selectedNetwork);
    }, [selectedCoin, selectedNetwork, fetchQuote]);

    useEffect(() => {
        const unsubscribe = onPaymentSetup(() => {
            return {
                type: emitResponse.responseTypes.SUCCESS,
                meta: {
                    paymentMethodData: {
                        seaxpay_coin: selectedCoin,
                        seaxpay_network: selectedNetwork,
                    },
                },
            };
        });
        return () => unsubscribe();
    }, [onPaymentSetup, emitResponse, selectedCoin, selectedNetwork]);

    const handleCoinChange = (e) => {
        const newCoin = e.target.value;
        const networks = getNetworksForCoin(newCoin);
        const newNetwork = pickBestNetwork(networks);
        setSelectedCoin(newCoin);
        if (newNetwork) {
            setSelectedNetwork(newNetwork);
        }
    };

    const handleNetworkChange = (e) => {
        setSelectedNetwork(e.target.value);
    };

    const networks = getNetworksForCoin(selectedCoin);
    const currentCoinInfo = supportedCoins[selectedCoin] || {};
    const sortedNetworkKeys = sortNetworkKeys(networks);
    const showHighFeeHint = isHighFeeNetwork(selectedNetwork);

    const formatCryptoAmount = (amount, coin) => {
        if (loading) return 'Loading...';
        if (!amount) return '0.000000 ' + coin;

        let amountStr = String(amount);

        if (amountStr.includes('.')) {
            amountStr = amountStr.replace(/\.?0+$/, '');
        }

        return amountStr + ' ' + coin;
    };


    return createElement('div', { className: 'seaxpay-blocks-payment', style: { padding: '10px 0' } },
        createElement('p', {
            style: { fontSize: '14px', fontWeight: '600', marginBottom: '8px', color: '#333' }
        }, 'Please Select a Currency'),

        createElement('div', {
            style: {
                display: 'flex',
                alignItems: 'center',
                border: '1px solid #ddd',
                borderRadius: '4px',
                padding: '12px 14px',
                marginBottom: '10px',
                backgroundColor: '#fff'
            }
        },
            currentCoinInfo.icon ? createElement('img', {
                src: currentCoinInfo.icon,
                alt: selectedCoin,
                style: { width: '28px', height: '28px', marginRight: '12px' }
            }) : createElement('span', { style: { marginRight: '12px', fontSize: '20px' } }, '💰'),

            createElement('div', { style: { flex: 1 } },
                createElement('div', {
                    style: {
                        fontSize: '16px',
                        fontWeight: '600',
                        color: loading ? '#999' : '#333',
                        marginBottom: '2px'
                    }
                }, formatCryptoAmount(cryptoAmount, selectedCoin)),

                createElement('select', {
                    value: selectedCoin,
                    onChange: handleCoinChange,
                    disabled: loading,
                    style: {
                        border: 'none',
                        outline: 'none',
                        fontSize: '13px',
                        color: '#666',
                        backgroundColor: 'transparent',
                        cursor: 'pointer',
                        paddingRight: '24px',
                        marginTop: '2px',
                        width: 'auto',
                        maxWidth: '200px'
                    }
                },
                    Object.keys(supportedCoins).map(coin =>
                        createElement('option', { key: coin, value: coin },
                            coin + ' - ' + (supportedCoins[coin].name || coin)
                        )
                    )
                )
            ),

            loading && createElement('span', {
                style: { fontSize: '12px', color: '#999' }
            }, '⏳')
        ),

        createElement('div', {
            style: {
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                padding: '10px 14px',
                borderTop: '1px solid #eee',
                fontSize: '14px',
                color: '#666'
            }
        },
            createElement('span', { style: { fontWeight: '500' } }, 'Payment Network:'),
            createElement('select', {
                value: selectedNetwork,
                onChange: handleNetworkChange,
                disabled: loading,
                style: {
                    border: 'none',
                    outline: 'none',
                    fontSize: '14px',
                    color: '#333',
                    fontWeight: '500',
                    backgroundColor: 'transparent',
                    cursor: 'pointer',
                    textAlign: 'right'
                }
            },
                sortedNetworkKeys.map(network => {
                    const meta = networks[network];
                    const eligible = isNetworkEligible(network, meta);
                    const min = meta && meta.min_amount_usd;
                    let label = meta.name + ' (' + network + ')';
                    if (!eligible && min) {
                        label += ' - min $' + min;
                    } else if (isHighFeeNetwork(network)) {
                        label += ' - high fee';
                    } else if (meta && meta.recommended) {
                        label = '\u2B50 ' + label;
                    }
                    return createElement('option', {
                        key: network,
                        value: network,
                        disabled: !eligible
                    }, label);
                })
            )
        ),

        showHighFeeHint && createElement('div', {
            style: {
                padding: '8px 14px',
                fontSize: '12px',
                color: '#8a6d3b',
                backgroundColor: '#fcf8e3',
                borderRadius: '4px',
                marginTop: '8px'
            }
        }, '\u26A0\uFE0F High network fee. Not recommended for small orders \u2014 consider a lower-fee network above.'),

        error && createElement('div', {
            style: {
                padding: '8px 14px',
                fontSize: '12px',
                color: '#e74c3c',
                backgroundColor: '#fdf2f2',
                borderRadius: '4px',
                marginTop: '8px'
            }
        }, error),

        !loading && !error && cryptoAmount > 0 && createElement('div', {
            style: {
                marginTop: '12px',
                padding: '12px 14px',
                backgroundColor: '#e8f5e9',
                borderRadius: '4px',
                border: '1px solid #c8e6c9'
            }
        },
            createElement('div', {
                style: { fontSize: '13px', color: '#2e7d32', marginBottom: '4px' }
            },
                createElement('strong', null, 'Estimated Payment: '),
                formatCryptoAmount(cryptoAmount, selectedCoin)
            ),
            exchangeRate > 0 && createElement('div', {
                style: { fontSize: '11px', color: '#666', marginTop: '4px' }
            }, 'Rate: 1 ' + selectedCoin + ' ≈ $' + parseFloat(exchangeRate).toLocaleString()),
            createElement('div', {
                style: { fontSize: '11px', color: '#666', marginTop: '6px', fontStyle: 'italic' }
            }, '💡 Payment address will be shown after order confirmation.')
        )
    );
};

const Label = (props) => {
    return createElement('span', null, 'Pay With Cryptocurrency');
};

const SeaxPayPaymentMethod = {
    name: 'seaxpay',
    label: createElement(Label, null),
    content: createElement(Content, null),
    edit: createElement(Content, null),
    canMakePayment: () => true,
    ariaLabel: 'Pay With Cryptocurrency',
    supports: {
        features: settings.supports || ['products'],
    },
};

registerPaymentMethod(SeaxPayPaymentMethod);
