import React, { useState, useEffect } from 'react';
import { StyleSheet, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type { CalcuttaEscrowProps } from '@bettoredge/types';
import { useCalcuttaEscrow } from '../hooks/useCalcuttaEscrow';
import { formatCurrency } from '../helpers/formatting';

export interface CalcuttaEscrowComponentProps {
    calcutta_competition_id: string;
    escrow?: CalcuttaEscrowProps;
    market_type: string;
    max_escrow?: number;
    player_balance?: number;
    onDepositFunds?: (amount: number) => void;
    onUpdate: (escrow: CalcuttaEscrowProps) => void;
    readOnly?: boolean;
}

type EscrowAction = 'transfer_in' | 'transfer_out';

const QUICK_AMOUNTS = [10, 25, 50, 100];

export const CalcuttaEscrow: React.FC<CalcuttaEscrowComponentProps> = ({
    calcutta_competition_id,
    escrow: initialEscrow,
    market_type,
    max_escrow,
    player_balance,
    onDepositFunds,
    onUpdate,
    readOnly,
}) => {
    const { theme } = useTheme();
    const { escrow: hookEscrow, loading, error, fetchEscrow, deposit, withdraw } = useCalcuttaEscrow(calcutta_competition_id);
    const [action, setAction] = useState<EscrowAction>('transfer_in');
    const [amount, setAmount] = useState('');

    const currentEscrow = hookEscrow ?? initialEscrow;

    useEffect(() => {
        if (!hookEscrow) {
            fetchEscrow();
        }
    }, [hookEscrow, fetchEscrow]);

    const available = Number(currentEscrow?.escrow_balance ?? 0);
    const committed = Number(currentEscrow?.committed_balance ?? 0);
    const total = available + committed;

    // Budget cap calculations
    const netDeposited = currentEscrow
        ? Number(currentEscrow.total_deposited) - Number(currentEscrow.total_withdrawn)
        : 0;
    const budgetRemaining = max_escrow != null && Number(max_escrow) > 0
        ? Math.max(0, Number(max_escrow) - netDeposited)
        : null;
    const budgetFullyDeposited = budgetRemaining !== null && budgetRemaining <= 0;
    const budgetPct = max_escrow != null && Number(max_escrow) > 0
        ? Math.min(100, (netDeposited / Number(max_escrow)) * 100)
        : null;

    const committedPct = total > 0 ? (committed / total) * 100 : 0;

    const numericAmount = parseFloat(amount) || 0;
    const hasBalance = player_balance != null;
    const insufficientBalance = hasBalance && action === 'transfer_in' && numericAmount > Number(player_balance);
    const shortfall = insufficientBalance ? numericAmount - Number(player_balance) : 0;
    const exceedsBudget = action === 'transfer_in' && budgetRemaining !== null && numericAmount > budgetRemaining;
    const exceedsWithdraw = action === 'transfer_out' && numericAmount > available;
    const [actionError, setActionError] = useState('');

    const isInvalidAmount = numericAmount <= 0 || exceedsBudget || exceedsWithdraw || (insufficientBalance && !onDepositFunds);

    const getValidationMessage = (): string => {
        if (numericAmount <= 0) return '';
        if (exceedsBudget) return `Budget cap: ${formatCurrency(Number(max_escrow), market_type)}. You can deposit up to ${formatCurrency(budgetRemaining ?? 0, market_type)} more.`;
        if (exceedsWithdraw) return `You only have ${formatCurrency(available, market_type)} available to withdraw.`;
        if (insufficientBalance && !onDepositFunds) return `Insufficient wallet balance. You have ${formatCurrency(player_balance, market_type)}.`;
        return '';
    };

    const validationMessage = getValidationMessage();

    const handleAction = async () => {
        if (isNaN(numericAmount) || numericAmount <= 0) return;
        setActionError('');
        if (insufficientBalance && onDepositFunds) {
            onDepositFunds(Math.ceil(shortfall * 100) / 100);
            return;
        }
        try {
            let result;
            if (action === 'transfer_in') {
                result = await deposit(numericAmount);
            } else {
                result = await withdraw(numericAmount);
            }
            if (result) {
                onUpdate(result);
                setAmount('');
                setActionError('');
            }
        } catch (e: any) {
            setActionError(e?.message || 'Transfer failed. Please try again.');
        }
    };

    const handleQuickAmount = (amt: number) => {
        // Cap quick amount to budget remaining for deposits
        if (action === 'transfer_in' && budgetRemaining !== null) {
            setAmount(String(Math.min(amt, budgetRemaining)));
        } else if (action === 'transfer_out') {
            setAmount(String(Math.min(amt, available)));
        } else {
            setAmount(String(amt));
        }
    };

    // ============================================
    // READ-ONLY: big KPI cards only
    // ============================================
    if (readOnly) {
        return (
            <View variant="transparent" style={styles.container}>
                <View variant="transparent" style={styles.kpiRow}>
                    <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                        <View variant="transparent" style={[styles.kpiIcon, { backgroundColor: theme.colors.primary.subtle }]}>
                            <Ionicons name="wallet-outline" size={20} color={theme.colors.primary.default} />
                        </View>
                        <Text variant="caption" color="tertiary" style={styles.kpiLabel}>Available</Text>
                        <Text variant="h3" bold>{formatCurrency(available, market_type)}</Text>
                    </View>
                    <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                        <View variant="transparent" style={[styles.kpiIcon, { backgroundColor: theme.colors.surface.base }]}>
                            <Ionicons name="lock-closed-outline" size={20} color={theme.colors.text.tertiary} />
                        </View>
                        <Text variant="caption" color="tertiary" style={styles.kpiLabel}>Committed</Text>
                        <Text variant="h3" bold>{formatCurrency(committed, market_type)}</Text>
                    </View>
                </View>

                {/* Usage bar */}
                <View variant="transparent" style={styles.barWrap}>
                    <View variant="transparent" style={[styles.barTrack, { backgroundColor: theme.colors.surface.base }]}>
                        <View variant="transparent" style={[styles.barFill, { width: `${Math.min(100, committedPct)}%`, backgroundColor: theme.colors.primary.default }]} />
                    </View>
                    <Text variant="caption" color="tertiary" style={styles.barLabel}>
                        {formatCurrency(committed, market_type)} committed of {formatCurrency(total, market_type)} total
                    </Text>
                </View>
            </View>
        );
    }

    // ============================================
    // INTERACTIVE: full escrow management
    // ============================================
    return (
        <View variant="transparent" style={styles.container}>
            {/* KPI Cards */}
            <View variant="transparent" style={styles.kpiRow}>
                <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                    <View variant="transparent" style={[styles.kpiIcon, { backgroundColor: theme.colors.primary.subtle }]}>
                        <Ionicons name="wallet-outline" size={20} color={theme.colors.primary.default} />
                    </View>
                    <Text variant="caption" color="tertiary" style={styles.kpiLabel}>Available</Text>
                    <Text variant="h3" bold>{formatCurrency(available, market_type)}</Text>
                </View>
                <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                    <View variant="transparent" style={[styles.kpiIcon, { backgroundColor: theme.colors.surface.base }]}>
                        <Ionicons name="lock-closed-outline" size={20} color={theme.colors.text.tertiary} />
                    </View>
                    <Text variant="caption" color="tertiary" style={styles.kpiLabel}>Committed</Text>
                    <Text variant="h3" bold>{formatCurrency(committed, market_type)}</Text>
                </View>
            </View>

            {/* Usage bar */}
            <View variant="transparent" style={styles.barWrap}>
                <View variant="transparent" style={[styles.barTrack, { backgroundColor: theme.colors.surface.base }]}>
                    <View variant="transparent" style={[styles.barFill, { width: `${Math.min(100, committedPct)}%`, backgroundColor: theme.colors.primary.default }]} />
                </View>
            </View>

            {/* Wallet balance */}
            {hasBalance && (
                <View variant="transparent" style={[styles.walletRow, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                    <Ionicons name="card-outline" size={16} color={theme.colors.text.tertiary} />
                    <Text variant="caption" color="secondary" style={{ marginLeft: 8, flex: 1 }}>Wallet Balance</Text>
                    <Text variant="body" bold>{formatCurrency(player_balance, market_type)}</Text>
                </View>
            )}

            {/* Budget cap */}
            {budgetRemaining !== null && (
                <View variant="transparent" style={styles.budgetWrap}>
                    <View variant="transparent" style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 6 }}>
                        <Text variant="caption" color="secondary">Budget Cap</Text>
                        <Text variant="caption" bold style={{ color: budgetFullyDeposited ? theme.colors.status.success : theme.colors.text.primary }}>
                            {budgetFullyDeposited ? 'Fully deposited' : `${formatCurrency(budgetRemaining, market_type)} remaining`}
                        </Text>
                    </View>
                    <View variant="transparent" style={[styles.barTrack, { backgroundColor: theme.colors.surface.base }]}>
                        <View variant="transparent" style={[styles.barFill, {
                            width: `${budgetPct ?? 0}%`,
                            backgroundColor: budgetFullyDeposited ? theme.colors.status.success : theme.colors.primary.default,
                        }]} />
                    </View>
                    <Text variant="caption" color="tertiary" style={{ marginTop: 4 }}>
                        {formatCurrency(netDeposited, market_type)} of {formatCurrency(Number(max_escrow), market_type)}
                    </Text>
                </View>
            )}

            {/* Transfer In / Out toggle */}
            <View variant="transparent" style={styles.toggleRow}>
                <TouchableOpacity
                    style={[
                        styles.toggleButton,
                        action === 'transfer_in'
                            ? { backgroundColor: theme.colors.primary.default }
                            : { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, borderWidth: 1 },
                    ]}
                    onPress={() => setAction('transfer_in')}
                    activeOpacity={0.7}
                >
                    <Ionicons
                        name="arrow-up-outline"
                        size={18}
                        color={action === 'transfer_in' ? '#FFFFFF' : theme.colors.text.secondary}
                    />
                    <Text
                        variant="body"
                        bold
                        style={{ color: action === 'transfer_in' ? '#FFFFFF' : theme.colors.text.secondary, marginLeft: 6 }}
                    >
                        Transfer In
                    </Text>
                </TouchableOpacity>
                <TouchableOpacity
                    style={[
                        styles.toggleButton,
                        { marginLeft: 10 },
                        action === 'transfer_out'
                            ? { backgroundColor: theme.colors.primary.default }
                            : { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, borderWidth: 1 },
                    ]}
                    onPress={() => setAction('transfer_out')}
                    activeOpacity={0.7}
                >
                    <Ionicons
                        name="arrow-down-outline"
                        size={18}
                        color={action === 'transfer_out' ? '#FFFFFF' : theme.colors.text.secondary}
                    />
                    <Text
                        variant="body"
                        bold
                        style={{ color: action === 'transfer_out' ? '#FFFFFF' : theme.colors.text.secondary, marginLeft: 6 }}
                    >
                        Transfer Out
                    </Text>
                </TouchableOpacity>
            </View>

            {/* Quick amount buttons */}
            <View variant="transparent" style={styles.quickRow}>
                {QUICK_AMOUNTS.map(amt => (
                    <TouchableOpacity
                        key={amt}
                        style={[styles.quickBtn, {
                            backgroundColor: numericAmount === amt ? theme.colors.primary.subtle : theme.colors.surface.elevated,
                            borderColor: numericAmount === amt ? theme.colors.primary.default : theme.colors.border.subtle,
                        }]}
                        onPress={() => handleQuickAmount(amt)}
                        activeOpacity={0.7}
                    >
                        <Text variant="body" bold style={{
                            color: numericAmount === amt ? theme.colors.primary.default : theme.colors.text.primary,
                        }}>
                            {formatCurrency(amt, market_type)}
                        </Text>
                    </TouchableOpacity>
                ))}
            </View>

            {/* Amount input + submit */}
            <View variant="transparent" style={styles.inputRow}>
                <View variant="transparent" style={[styles.inputWrap, {
                    borderColor: insufficientBalance ? theme.colors.status.error : theme.colors.border.subtle,
                    backgroundColor: theme.colors.surface.input,
                }]}>
                    <Text variant="body" color="tertiary" style={{ marginRight: 4 }}>$</Text>
                    <TextInput
                        style={[styles.input, { color: theme.colors.text.primary }]}
                        value={amount}
                        onChangeText={setAmount}
                        keyboardType="decimal-pad"
                        placeholder="0.00"
                        placeholderTextColor={theme.colors.text.tertiary}
                    />
                </View>
                <TouchableOpacity
                    style={[styles.submitBtn, {
                        backgroundColor: insufficientBalance && onDepositFunds
                            ? theme.colors.status.error
                            : (loading || isInvalidAmount)
                                ? theme.colors.surface.elevated
                                : theme.colors.status.success,
                    }]}
                    onPress={handleAction}
                    disabled={loading || (isInvalidAmount && !(insufficientBalance && onDepositFunds))}
                    activeOpacity={0.7}
                >
                    {loading ? (
                        <ActivityIndicator size="small" color="#FFFFFF" />
                    ) : (
                        <>
                            <Ionicons
                                name={action === 'transfer_in' ? 'arrow-up-circle' : 'arrow-down-circle'}
                                size={20}
                                color={isInvalidAmount ? theme.colors.text.tertiary : '#FFFFFF'}
                            />
                            <Text
                                variant="body"
                                bold
                                style={{
                                    color: isInvalidAmount ? theme.colors.text.tertiary : '#FFFFFF',
                                    marginLeft: 6,
                                }}
                            >
                                {insufficientBalance
                                    ? 'Deposit & Transfer'
                                    : action === 'transfer_in'
                                        ? 'Transfer In'
                                        : 'Transfer Out'}
                            </Text>
                        </>
                    )}
                </TouchableOpacity>
            </View>

            {/* Validation message (budget cap, withdraw limit, etc.) */}
            {validationMessage ? (
                <View variant="transparent" style={[styles.warningRow, { backgroundColor: '#D9770615' }]}>
                    <Ionicons name="information-circle-outline" size={16} color="#D97706" />
                    <Text variant="caption" style={{ color: '#D97706', marginLeft: 8, flex: 1 }}>
                        {validationMessage}
                    </Text>
                </View>
            ) : null}

            {/* Insufficient wallet balance */}
            {insufficientBalance && !validationMessage && (
                <View variant="transparent" style={[styles.warningRow, { backgroundColor: theme.colors.status.error + '10' }]}>
                    <Ionicons name="warning-outline" size={16} color={theme.colors.status.error} />
                    <Text variant="caption" style={{ color: theme.colors.status.error, marginLeft: 8, flex: 1 }}>
                        You need {formatCurrency(shortfall, market_type)} more in your wallet. Tap to deposit first.
                    </Text>
                </View>
            )}

            {/* API error */}
            {(error || actionError) && (
                <View variant="transparent" style={[styles.warningRow, { backgroundColor: theme.colors.status.error + '10' }]}>
                    <Ionicons name="alert-circle-outline" size={16} color={theme.colors.status.error} />
                    <Text variant="caption" style={{ color: theme.colors.status.error, marginLeft: 8, flex: 1 }}>
                        {actionError || error}
                    </Text>
                </View>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        padding: 14,
    },
    // KPI Cards
    kpiRow: {
        flexDirection: 'row',
        gap: 10,
    },
    kpiCard: {
        flex: 1,
        borderRadius: 12,
        borderWidth: 1,
        padding: 14,
        alignItems: 'center',
    },
    kpiIcon: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: 'center',
        justifyContent: 'center',
        marginBottom: 8,
    },
    kpiLabel: {
        marginBottom: 2,
    },
    // Usage bar
    barWrap: {
        marginTop: 12,
    },
    barTrack: {
        height: 6,
        borderRadius: 3,
        overflow: 'hidden',
    },
    barFill: {
        height: 6,
        borderRadius: 3,
    },
    barLabel: {
        marginTop: 4,
        textAlign: 'center',
    },
    // Wallet
    walletRow: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 12,
        borderRadius: 10,
        borderWidth: 1,
        marginTop: 12,
    },
    // Budget
    budgetWrap: {
        marginTop: 12,
    },
    // Transfer toggle
    toggleRow: {
        flexDirection: 'row',
        marginTop: 16,
    },
    toggleButton: {
        flex: 1,
        flexDirection: 'row',
        height: 48,
        borderRadius: 10,
        alignItems: 'center',
        justifyContent: 'center',
    },
    // Quick amounts
    quickRow: {
        flexDirection: 'row',
        marginTop: 12,
        gap: 8,
    },
    quickBtn: {
        flex: 1,
        height: 40,
        borderRadius: 8,
        borderWidth: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    // Input
    inputRow: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 12,
        gap: 10,
    },
    inputWrap: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        height: 48,
        borderRadius: 10,
        borderWidth: 1,
        paddingHorizontal: 14,
    },
    input: {
        flex: 1,
        fontSize: 18,
        lineHeight: 24,
        height: 48,
        padding: 0,
    },
    submitBtn: {
        flexDirection: 'row',
        height: 48,
        paddingHorizontal: 16,
        borderRadius: 10,
        alignItems: 'center',
        justifyContent: 'center',
    },
    // Warnings
    warningRow: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 12,
        borderRadius: 10,
        marginTop: 10,
    },
});
