import React, { useState, useEffect } from 'react';
import { StyleSheet, TouchableOpacity, LayoutAnimation, Platform, UIManager } 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';
import { CalcuttaEscrow } from './CalcuttaEscrow';

if (Platform.OS === 'android' && UIManager.setLayoutAnimationEnabledExperimental) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
}

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

export const EscrowWidget: React.FC<EscrowWidgetProps> = ({
    calcutta_competition_id,
    market_type,
    max_escrow,
    player_balance,
    onDepositFunds,
    readOnly,
    onUpdate,
    initialExpanded,
}) => {
    const { theme } = useTheme();
    const { escrow, fetchEscrow } = useCalcuttaEscrow(calcutta_competition_id);
    const [expanded, setExpanded] = useState(initialExpanded ?? false);

    useEffect(() => {
        if (initialExpanded) setExpanded(true);
    }, [initialExpanded]);

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

    const available = Number(escrow?.escrow_balance ?? 0);
    const committed = Number(escrow?.committed_balance ?? 0);
    const hasFunds = available > 0 || committed > 0;

    const toggle = () => {
        LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
        setExpanded(!expanded);
    };

    return (
        <View variant="transparent" style={[styles.container, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
            {/* Collapsed header — always visible */}
            <TouchableOpacity
                style={styles.header}
                onPress={readOnly ? undefined : toggle}
                activeOpacity={readOnly ? 1 : 0.7}
            >
                <View variant="transparent" style={[styles.iconCircle, { backgroundColor: hasFunds ? theme.colors.status.successSubtle : theme.colors.primary.subtle }]}>
                    <Ionicons
                        name="wallet-outline"
                        size={18}
                        color={hasFunds ? theme.colors.status.success : theme.colors.primary.default}
                    />
                </View>
                <View variant="transparent" style={styles.headerText}>
                    <Text variant="body" bold>
                        {formatCurrency(available, market_type)}
                        <Text variant="caption" color="tertiary"> available</Text>
                    </Text>
                    {committed > 0 && (
                        <Text variant="caption" color="tertiary">
                            {formatCurrency(committed, market_type)} committed
                        </Text>
                    )}
                </View>
                {!readOnly && (
                    <View variant="transparent" style={[styles.addBtn, { backgroundColor: theme.colors.primary.default }]}>
                        <Ionicons name={expanded ? 'chevron-up' : 'add'} size={18} color="#FFFFFF" />
                        {!expanded && (
                            <Text variant="caption" bold style={{ color: '#FFFFFF', marginLeft: 4 }}>
                                {hasFunds ? 'Manage' : 'Add Funds'}
                            </Text>
                        )}
                    </View>
                )}
            </TouchableOpacity>

            {/* Budget cap bar (always visible if applicable) */}
            {max_escrow != null && Number(max_escrow) > 0 && (
                <View variant="transparent" style={styles.budgetBar}>
                    <View variant="transparent" style={[styles.barTrack, { backgroundColor: theme.colors.surface.base }]}>
                        <View variant="transparent" style={[styles.barFill, {
                            width: `${Math.min(100, ((Number(escrow?.total_deposited ?? 0) - Number(escrow?.total_withdrawn ?? 0)) / Number(max_escrow)) * 100)}%`,
                            backgroundColor: theme.colors.primary.default,
                        }]} />
                    </View>
                    <Text variant="caption" color="tertiary" style={{ marginTop: 4 }}>
                        Budget: {formatCurrency(Number(max_escrow), market_type)}
                    </Text>
                </View>
            )}

            {/* Expanded: full escrow management */}
            {expanded && !readOnly && (
                <View variant="transparent" style={styles.expandedContent}>
                    <CalcuttaEscrow
                        calcutta_competition_id={calcutta_competition_id}
                        escrow={escrow ?? undefined}
                        market_type={market_type}
                        max_escrow={max_escrow}
                        player_balance={player_balance}
                        onDepositFunds={onDepositFunds}
                        onUpdate={(updated) => {
                            fetchEscrow();
                            onUpdate?.();
                        }}
                    />
                </View>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        borderRadius: 14,
        borderWidth: 1,
        overflow: 'hidden',
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 14,
    },
    iconCircle: {
        width: 36,
        height: 36,
        borderRadius: 18,
        alignItems: 'center',
        justifyContent: 'center',
    },
    headerText: {
        flex: 1,
        marginLeft: 12,
    },
    addBtn: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 12,
        paddingVertical: 6,
        borderRadius: 20,
    },
    budgetBar: {
        paddingHorizontal: 14,
        paddingBottom: 12,
    },
    barTrack: {
        height: 4,
        borderRadius: 2,
        overflow: 'hidden',
    },
    barFill: {
        height: 4,
        borderRadius: 2,
    },
    expandedContent: {
        borderTopWidth: 1,
        borderTopColor: 'rgba(128,128,128,0.15)',
    },
});
