import React, { useState, useEffect, useRef } from 'react';
import { StyleSheet, TouchableOpacity } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type { CalcuttaCompetitionProps, CalcuttaEscrowProps, CalcuttaBidProps, CalcuttaAuctionItemProps } from '@bettoredge/types';
import type { CalcuttaLifecycleState } from '../../helpers/lifecycleState';
import { formatCurrency } from '../../helpers/formatting';

interface SealedBidStatusBarProps {
    competition: CalcuttaCompetitionProps;
    escrow?: CalcuttaEscrowProps;
    my_bids: CalcuttaBidProps[];
    items: CalcuttaAuctionItemProps[];
    totalItems: number;
    market_type: string;
    player_id?: string;
    lifecycleState: CalcuttaLifecycleState;
    auctionExpired?: boolean;
    isParticipant?: boolean;
    onEscrowTap: () => void;
    onLeave?: () => void;
    leaving?: boolean;
}

const getTimerColor = (msLeft: number) => {
    if (msLeft > 3600000) return '#10B981';
    if (msLeft > 600000) return '#F59E0B';
    return '#EF4444';
};

export const SealedBidStatusBar: React.FC<SealedBidStatusBarProps> = ({
    competition,
    escrow,
    my_bids,
    items,
    totalItems,
    market_type,
    player_id,
    lifecycleState,
    auctionExpired,
    isParticipant,
    onEscrowTap,
    onLeave,
    leaving,
}) => {
    const { theme } = useTheme();
    const [timeLeft, setTimeLeft] = useState('');
    const [msLeft, setMsLeft] = useState(Infinity);
    const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

    const timerTarget = lifecycleState === 'auctioning'
        ? competition.auction_end_datetime
        : lifecycleState === 'scheduled'
            ? competition.scheduled_datetime
            : undefined;

    useEffect(() => {
        if (!timerTarget) {
            setTimeLeft('');
            setMsLeft(0);
            return;
        }

        const update = () => {
            const end = new Date(timerTarget).getTime();
            const diff = end - Date.now();
            setMsLeft(diff);

            if (diff <= 0) {
                setTimeLeft(lifecycleState === 'auctioning' ? 'Closed' : 'Starting...');
                if (timerRef.current) clearInterval(timerRef.current);
                return;
            }

            const d = Math.floor(diff / 86400000);
            const h = Math.floor((diff % 86400000) / 3600000);
            const m = Math.floor((diff % 3600000) / 60000);
            const s = Math.floor((diff % 60000) / 1000);

            if (d > 0) setTimeLeft(`${d}d ${h}h`);
            else if (h > 0) setTimeLeft(`${h}h ${m}m`);
            else setTimeLeft(`${m}:${s.toString().padStart(2, '0')}`);
        };

        update();
        timerRef.current = setInterval(update, 1000);
        return () => { if (timerRef.current) clearInterval(timerRef.current); };
    }, [timerTarget, lifecycleState]);

    const escrowBalance = Number(escrow?.escrow_balance ?? 0);
    const committed = Number(escrow?.committed_balance ?? 0);
    const total = escrowBalance + committed;
    // All items I purchased (active + eliminated)
    const myPurchasedItems = items.filter(i => i.winning_player_id === player_id);

    // ============================================
    // PENDING
    // ============================================
    if (lifecycleState === 'pending') {
        return (
            <View variant="transparent" style={[styles.container, { borderColor: theme.colors.border.subtle }]}>
                
                <View variant="transparent" style={styles.cells}>
                    <View variant="transparent" style={styles.cell}>
                        <Ionicons name="lock-closed-outline" size={14} color="#F59E0B" />
                        <Text variant="caption" bold style={{ color: '#F59E0B', marginLeft: 4 }}>
                            Coming Soon
                        </Text>
                    </View>
                    <View variant="transparent" style={styles.cell}>
                        <Text variant="caption" color="secondary">Items: {totalItems}</Text>
                    </View>
                    <View variant="transparent" style={styles.cell} />
                </View>
            </View>
        );
    }

    // ============================================
    // SCHEDULED
    // ============================================
    if (lifecycleState === 'scheduled') {
        return (
            <View variant="transparent" style={[styles.container, { borderColor: theme.colors.border.subtle }]}>
                
                <View variant="transparent" style={styles.cells}>
                    <View variant="transparent" style={styles.cell}>
                        <Ionicons name="calendar-outline" size={14} color="#3B82F6" />
                        <Text variant="caption" bold style={{ color: '#3B82F6', marginLeft: 4 }}>
                            {timeLeft ? `Starts ${timeLeft}` : 'Scheduled'}
                        </Text>
                    </View>
                    <TouchableOpacity style={styles.cell} onPress={onEscrowTap} activeOpacity={0.7}>
                        <Ionicons name="wallet-outline" size={14} color={theme.colors.text.secondary} />
                        <Text variant="caption" bold style={{ marginLeft: 4 }}>
                            {formatCurrency(escrowBalance, market_type)}
                        </Text>
                    </TouchableOpacity>
                    <View variant="transparent" style={styles.cell}>
                        <Ionicons name="people-outline" size={14} color={theme.colors.text.secondary} />
                        <Text variant="caption" bold style={{ marginLeft: 4 }}>
                            {items.length > 0 ? `${totalItems} items` : '0'}
                        </Text>
                    </View>
                </View>
            </View>
        );
    }

    // ============================================
    // AUCTIONING — big KPI-style bar
    // ============================================
    if (lifecycleState === 'auctioning') {
        const activeBids = my_bids.filter(b => b.bid_status === 'active').length;
        const timerColor = auctionExpired ? '#F59E0B' : getTimerColor(msLeft);

        // Safe auction metrics (no bid amount leaks)
        const totalBidsPlaced = items.reduce((s, i) => s + (i.bid_count ?? 0), 0);
        const itemsWithBids = items.filter(i => (i.bid_count ?? 0) > 0).length;
        const minPot = competition.min_bid * totalItems;
        const myTotalBid = my_bids
            .filter(b => b.bid_status === 'active')
            .reduce((s, b) => s + Number(b.bid_amount), 0);

        return (
            <View variant="transparent" style={[styles.auctionContainer, { borderColor: theme.colors.border.subtle }]}>

                {/* Timer row */}
                <View variant="transparent" style={styles.timerRow}>
                    <Ionicons name={auctionExpired ? 'hourglass-outline' : 'timer-outline'} size={18} color={timerColor} />
                    <Text variant="h3" bold style={{ color: timerColor, marginLeft: 6 }}>
                        {auctionExpired ? 'Closing...' : timeLeft}
                    </Text>
                </View>

                {/* Auction Activity (safe metrics only) */}
                <View variant="transparent" style={[styles.potTracker, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                    <View variant="transparent" style={styles.potHeader}>
                        <Ionicons name="pulse-outline" size={16} color={theme.colors.primary.default} />
                        <Text variant="caption" bold style={{ color: theme.colors.primary.default, marginLeft: 6 }}>Auction Activity</Text>
                    </View>
                    <View variant="transparent" style={styles.potRow}>
                        <View variant="transparent" style={styles.potItem}>
                            <Text variant="h3" bold>{itemsWithBids}<Text variant="caption" color="tertiary">/{totalItems}</Text></Text>
                            <Text variant="caption" color="tertiary">Items Bid</Text>
                        </View>
                        <View variant="transparent" style={[styles.potDivider, { backgroundColor: theme.colors.border.subtle }]} />
                        <View variant="transparent" style={styles.potItem}>
                            <Text variant="h3" bold>{totalBidsPlaced}</Text>
                            <Text variant="caption" color="tertiary">Total Bids</Text>
                        </View>
                        <View variant="transparent" style={[styles.potDivider, { backgroundColor: theme.colors.border.subtle }]} />
                        <View variant="transparent" style={styles.potItem}>
                            <Text variant="h3" bold>{formatCurrency(minPot, market_type)}</Text>
                            <Text variant="caption" color="tertiary">Min Pot</Text>
                        </View>
                    </View>
                </View>

                {/* My Escrow KPIs — only for participants */}
                {isParticipant && (
                    <View variant="transparent" style={styles.kpiRow}>
                        <TouchableOpacity
                            style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}
                            onPress={onEscrowTap}
                            activeOpacity={0.7}
                        >
                            <Ionicons name="wallet-outline" size={16} color={theme.colors.primary.default} />
                            <Text variant="caption" color="tertiary" style={{ marginTop: 2 }}>Available</Text>
                            <Text variant="body" bold>{formatCurrency(escrowBalance, market_type)}</Text>
                        </TouchableOpacity>

                        <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                            <Ionicons name="pricetag-outline" size={16} color={theme.colors.text.secondary} />
                            <Text variant="caption" color="tertiary" style={{ marginTop: 2 }}>My Bids</Text>
                            <Text variant="body" bold>{formatCurrency(myTotalBid, market_type)}</Text>
                        </View>

                        <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                            <Ionicons name="pricetag-outline" size={16} color={theme.colors.text.secondary} />
                            <Text variant="caption" color="tertiary" style={{ marginTop: 2 }}>My Items</Text>
                            <Text variant="body" bold>{activeBids}<Text variant="caption" color="tertiary">/{totalItems}</Text></Text>
                        </View>
                    </View>
                )}

                {/* Transfer actions — only for participants */}
                {isParticipant && <View variant="transparent" style={styles.transferRow}>
                    <TouchableOpacity
                        style={[styles.transferBtn, { backgroundColor: theme.colors.primary.default }]}
                        onPress={onEscrowTap}
                        activeOpacity={0.7}
                    >
                        <Ionicons name="arrow-down-outline" size={16} color="#FFFFFF" />
                        <Text variant="caption" bold style={{ color: '#FFFFFF', marginLeft: 4 }}>
                            Transfer In
                        </Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={[styles.transferBtn, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, borderWidth: 1 }]}
                        onPress={onEscrowTap}
                        activeOpacity={0.7}
                    >
                        <Ionicons name="arrow-up-outline" size={16} color={theme.colors.text.secondary} />
                        <Text variant="caption" bold style={{ color: theme.colors.text.secondary, marginLeft: 4 }}>
                            Transfer Out
                        </Text>
                    </TouchableOpacity>
                </View>}

                {/* Leave button — only when: not expired, no active bids, no escrow balance */}
                {onLeave && !auctionExpired && activeBids === 0 && escrowBalance === 0 && committed === 0 && (
                    <TouchableOpacity
                        style={styles.leaveBtn}
                        onPress={onLeave}
                        disabled={leaving}
                        activeOpacity={0.7}
                    >
                        <Ionicons name="exit-outline" size={16} color="#EF4444" />
                        <Text variant="caption" bold style={{ color: '#EF4444', marginLeft: 6 }}>
                            {leaving ? 'Leaving...' : 'Leave Auction'}
                        </Text>
                    </TouchableOpacity>
                )}
            </View>
        );
    }

    // ============================================
    // TOURNAMENT
    // ============================================
    if (lifecycleState === 'tournament') {
        const totalPurchased = myPurchasedItems.reduce((s, i) => s + Number(i.winning_bid), 0);
        const stillAlive = myPurchasedItems.filter(i => i.status !== 'eliminated').length;

        return (
            <View variant="transparent" style={[styles.auctionContainer, { borderColor: theme.colors.border.subtle }]}>

                <View variant="transparent" style={styles.kpiRow}>
                    <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                        <Ionicons name="ellipse" size={8} color="#10B981" />
                        <Text variant="caption" color="tertiary" style={{ marginTop: 2 }}>Status</Text>
                        <Text variant="body" bold style={{ color: '#8B5CF6' }}>In Progress</Text>
                    </View>

                    <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                        <Ionicons name="cart-outline" size={16} color={theme.colors.primary.default} />
                        <Text variant="caption" color="tertiary" style={{ marginTop: 2 }}>Purchased</Text>
                        <Text variant="body" bold>{myPurchasedItems.length} <Text variant="caption" color="tertiary">({stillAlive} alive)</Text></Text>
                    </View>

                    <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                        <Ionicons name="cash-outline" size={16} color={theme.colors.text.secondary} />
                        <Text variant="caption" color="tertiary" style={{ marginTop: 2 }}>Spent</Text>
                        <Text variant="body" bold>{formatCurrency(totalPurchased, market_type)}</Text>
                    </View>
                </View>
            </View>
        );
    }

    // ============================================
    // COMPLETED
    // ============================================
    const totalPurchased = myPurchasedItems.reduce((s, i) => s + Number(i.winning_bid), 0);
    return (
        <View variant="transparent" style={[styles.auctionContainer, { borderColor: theme.colors.border.subtle }]}>

            <View variant="transparent" style={styles.kpiRow}>
                <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                    <Ionicons name="checkmark-circle" size={16} color={theme.colors.status.success} />
                    <Text variant="caption" color="tertiary" style={{ marginTop: 2 }}>Status</Text>
                    <Text variant="body" bold style={{ color: theme.colors.status.success }}>Completed</Text>
                </View>

                <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                    <Ionicons name="cart-outline" size={16} color={theme.colors.primary.default} />
                    <Text variant="caption" color="tertiary" style={{ marginTop: 2 }}>Purchased</Text>
                    <Text variant="body" bold>{myPurchasedItems.length}</Text>
                </View>

                <View variant="transparent" style={[styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                    <Ionicons name="cash-outline" size={16} color={theme.colors.text.secondary} />
                    <Text variant="caption" color="tertiary" style={{ marginTop: 2 }}>Spent</Text>
                    <Text variant="body" bold>{formatCurrency(totalPurchased, market_type)}</Text>
                </View>
            </View>
        </View>
    );
};

const styles = StyleSheet.create({
    // Compact container for pending/scheduled
    container: {
        borderBottomWidth: 1,
        paddingTop: 8,
        paddingHorizontal: 12,
        paddingBottom: 6,
    },
    cells: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    cell: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    // Full KPI container for auctioning/tournament/completed
    auctionContainer: {
        borderBottomWidth: 1,
        paddingHorizontal: 12,
        paddingVertical: 10,
    },
    timerRow: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginBottom: 10,
    },
    potTracker: {
        borderRadius: 12,
        borderWidth: 1,
        padding: 12,
        marginBottom: 10,
    },
    potHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 10,
    },
    potRow: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    potItem: {
        flex: 1,
        alignItems: 'center',
    },
    potDivider: {
        width: 1,
        height: 32,
    },
    kpiRow: {
        flexDirection: 'row',
        gap: 8,
    },
    kpiCard: {
        flex: 1,
        borderRadius: 10,
        borderWidth: 1,
        paddingVertical: 10,
        paddingHorizontal: 8,
        alignItems: 'center',
    },
    transferRow: {
        flexDirection: 'row',
        gap: 8,
        marginTop: 10,
    },
    transferBtn: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        height: 36,
        borderRadius: 8,
    },
    leaveBtn: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 10,
        paddingVertical: 8,
    },
});
