import React, { useMemo, useState } from 'react';
import { StyleSheet, TouchableOpacity, FlatList, Image } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type { CalcuttaAuctionItemProps, CalcuttaBidProps, CalcuttaEscrowProps, CalcuttaItemResultProps, CalcuttaRoundProps } from '@bettoredge/types';
import type { ItemImageMap } from '../../hooks/useCalcuttaItemImages';
import type { CalcuttaLifecycleState } from '../../helpers/lifecycleState';
import { formatCurrency, getBidStatusColor, getStatusLabel } from '../../helpers/formatting';

interface SealedBidMyBidsTabProps {
    items: CalcuttaAuctionItemProps[];
    my_bids: CalcuttaBidProps[];
    escrow?: CalcuttaEscrowProps;
    market_type: string;
    player_id?: string;
    lifecycleState: CalcuttaLifecycleState;
    itemImages?: ItemImageMap;
    item_results?: CalcuttaItemResultProps[];
    rounds?: CalcuttaRoundProps[];
    onCancelBid: (calcutta_bid_id: string) => void;
    onUpdateBid: (calcutta_auction_item_id: string) => void;
    cancelLoading: boolean;
    auctionExpired?: boolean;
    listHeader?: React.ReactNode;
}

interface BidRow {
    bid: CalcuttaBidProps;
    item?: CalcuttaAuctionItemProps;
}

export const SealedBidMyBidsTab: React.FC<SealedBidMyBidsTabProps> = ({
    items,
    my_bids,
    escrow,
    market_type,
    player_id,
    lifecycleState,
    itemImages,
    item_results = [],
    rounds = [],
    onCancelBid,
    onUpdateBid,
    cancelLoading,
    auctionExpired,
    listHeader,
}) => {
    const { theme } = useTheme();
    const [expandedItemId, setExpandedItemId] = useState<string | null>(null);

    const isPostAuction = lifecycleState === 'tournament' || lifecycleState === 'completed';
    const isPreAuction = lifecycleState === 'pending' || lifecycleState === 'scheduled';

    // All items I won at auction — includes sold (active) AND eliminated
    const myItems = useMemo(
        () => items.filter(i => i.winning_player_id === player_id),
        [items, player_id],
    );

    // For backward compat / badge counts — only active (non-eliminated) items
    const wonItems = useMemo(
        () => myItems.filter(i => i.status === 'sold'),
        [myItems],
    );

    const totalSpent = useMemo(
        () => myItems.reduce((s, i) => s + Number(i.winning_bid), 0),
        [myItems],
    );

    const activeBids = useMemo(
        () => my_bids.filter(b => b.bid_status === 'active'),
        [my_bids],
    );

    const rows: BidRow[] = useMemo(
        () => activeBids.map(bid => ({
            bid,
            item: items.find(i => i.calcutta_auction_item_id === bid.calcutta_auction_item_id),
        })),
        [activeBids, items],
    );

    const totalCommitted = useMemo(
        () => activeBids.reduce((sum, b) => sum + Number(b.bid_amount), 0),
        [activeBids],
    );

    const budgetRemaining = escrow ? Number(escrow.escrow_balance) : 0;

    // Build per-item result map for tournament/completed
    const itemResultMap = useMemo(() => {
        const map: Record<string, CalcuttaItemResultProps[]> = {};
        for (const r of item_results) {
            const key = r.calcutta_auction_item_id;
            if (!map[key]) map[key] = [];
            map[key].push(r);
        }
        return map;
    }, [item_results]);

    // Round name lookup
    const roundNameMap = useMemo(() => {
        const map: Record<number, string> = {};
        for (const r of rounds) map[r.round_number] = r.round_name;
        return map;
    }, [rounds]);

    // ============================================
    // PENDING / SCHEDULED — Empty state
    // ============================================
    if (isPreAuction) {
        return (
            <View variant="transparent" style={styles.container}>
                <>{listHeader}</>
                <View variant="transparent" style={styles.emptyContainer}>
                    <Ionicons name="time-outline" size={40} color={theme.colors.text.tertiary} />
                    <Text variant="body" color="tertiary" style={{ marginTop: 12 }}>Bidding hasn't started yet</Text>
                    <Text variant="caption" color="tertiary" style={{ marginTop: 4, textAlign: 'center' }}>
                        You'll be able to place bids once the auction begins
                    </Text>
                </View>
            </View>
        );
    }

    // ============================================
    // TOURNAMENT / COMPLETED — "My Items" ownership view with round results
    // ============================================
    if (isPostAuction) {
        if (myItems.length === 0) {
            return (
                <View variant="transparent" style={styles.container}>
                    <>{listHeader}</>
                    <View variant="transparent" style={styles.emptyContainer}>
                        <Ionicons name="ribbon-outline" size={40} color={theme.colors.text.tertiary} />
                        <Text variant="body" color="tertiary" style={{ marginTop: 12 }}>No items won</Text>
                        <Text variant="caption" color="tertiary" style={{ marginTop: 4, textAlign: 'center' }}>
                            You didn't win any items in this auction
                        </Text>
                    </View>
                </View>
            );
        }

        const totalEarned = myItems.reduce((s, i) => {
            const results = itemResultMap[i.calcutta_auction_item_id] || [];
            return s + results.reduce((rs, r) => rs + Number(r.payout_earned || 0), 0);
        }, 0);
        const totalROI = totalEarned - totalSpent;

        return (
            <View variant="transparent" style={styles.container}>
                <FlatList
                    data={myItems}
                    keyExtractor={i => i.calcutta_auction_item_id}
                    contentContainerStyle={styles.list}
                    ListHeaderComponent={
                        <View variant="transparent">
                            <>{listHeader}</>
                            <View variant="transparent" style={[styles.summary, {
                                backgroundColor: totalROI >= 0 ? theme.colors.status.successSubtle : theme.colors.status.error + '08',
                                borderColor: totalROI >= 0 ? theme.colors.status.success + '40' : theme.colors.status.error + '30',
                            }]}>
                                <View variant="transparent" style={styles.summaryItem}>
                                    <Ionicons name="trophy" size={20} color="#F59E0B" />
                                    <Text variant="caption" color="secondary" style={{ marginTop: 4 }}>Items</Text>
                                    <Text variant="h3" bold>{myItems.length}</Text>
                                </View>
                                <View variant="transparent" style={[styles.summaryItem, { borderLeftWidth: 1, borderColor: theme.colors.border.subtle }]}>
                                    <Ionicons name="arrow-down-circle-outline" size={20} color={theme.colors.text.tertiary} />
                                    <Text variant="caption" color="secondary" style={{ marginTop: 4 }}>Spent</Text>
                                    <Text variant="h3" bold>{formatCurrency(totalSpent, market_type)}</Text>
                                </View>
                                <View variant="transparent" style={[styles.summaryItem, { borderLeftWidth: 1, borderColor: theme.colors.border.subtle }]}>
                                    <Ionicons name="arrow-up-circle-outline" size={20} color={theme.colors.status.success} />
                                    <Text variant="caption" color="secondary" style={{ marginTop: 4 }}>Earned</Text>
                                    <Text variant="h3" bold style={{ color: theme.colors.status.success }}>{formatCurrency(totalEarned, market_type)}</Text>
                                </View>
                            </View>
                            {/* ROI banner */}
                            <View variant="transparent" style={[styles.roiBanner, {
                                backgroundColor: totalROI >= 0 ? theme.colors.status.successSubtle : theme.colors.status.error + '10',
                            }]}>
                                <Text variant="caption" bold style={{ color: totalROI >= 0 ? theme.colors.status.success : theme.colors.status.error }}>
                                    ROI: {totalROI >= 0 ? '+' : ''}{formatCurrency(totalROI, market_type)}
                                </Text>
                            </View>
                            <Text variant="caption" color="tertiary" style={styles.sectionLabel}>Your Items</Text>
                        </View>
                    }
                    renderItem={({ item }) => {
                        const results = itemResultMap[item.calcutta_auction_item_id] || [];
                        const totalPayout = results.reduce((s, r) => s + Number(r.payout_earned || 0), 0);
                        const itemROI = totalPayout - Number(item.winning_bid);
                        const isEliminated = item.status === 'eliminated';
                        const isExpanded = expandedItemId === item.calcutta_auction_item_id;

                        return (
                            <TouchableOpacity
                                activeOpacity={0.7}
                                onPress={() => setExpandedItemId(isExpanded ? null : item.calcutta_auction_item_id)}
                                style={[styles.ownedCard, {
                                    backgroundColor: theme.colors.surface.elevated,
                                    borderColor: isEliminated
                                        ? theme.colors.status.error + '30'
                                        : itemROI > 0
                                            ? theme.colors.status.success + '40'
                                            : theme.colors.border.subtle,
                                    opacity: isEliminated ? 0.8 : 1,
                                }]}
                            >
                                <View variant="transparent" style={styles.ownedRow}>
                                    <View variant="transparent" style={[styles.ownedIcon, {
                                        backgroundColor: isEliminated ? theme.colors.status.error + '10' : theme.colors.status.successSubtle,
                                        overflow: 'hidden',
                                    }]}>
                                        {(itemImages?.[item.item_id]?.url || item.item_image?.url) ? (
                                            <Image source={{ uri: itemImages?.[item.item_id]?.url || item.item_image?.url }} style={styles.ownedItemImage} resizeMode="contain" />
                                        ) : isEliminated ? (
                                            <Ionicons name="close-circle" size={18} color={theme.colors.status.error} />
                                        ) : (
                                            <Ionicons name="trophy" size={18} color="#F59E0B" />
                                        )}
                                    </View>
                                    <View variant="transparent" style={{ flex: 1 }}>
                                        <Text variant="body" bold numberOfLines={1}>{item.item_name}</Text>
                                        <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginTop: 2 }}>
                                            {isEliminated && (
                                                <Text variant="caption" bold style={{ color: theme.colors.status.error, fontSize: 10, lineHeight: 13, marginRight: 6 }}>ELIMINATED</Text>
                                            )}
                                            {item.seed != null && (
                                                <Text variant="caption" color="tertiary">Seed #{item.seed}</Text>
                                            )}
                                        </View>
                                    </View>
                                    <View variant="transparent" style={{ alignItems: 'flex-end' }}>
                                        <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>ROI</Text>
                                        <Text variant="body" bold style={{
                                            color: itemROI > 0
                                                ? theme.colors.status.success
                                                : itemROI < 0
                                                    ? theme.colors.status.error
                                                    : theme.colors.text.primary,
                                        }}>
                                            {itemROI >= 0 ? '+' : ''}{formatCurrency(itemROI, market_type)}
                                        </Text>
                                    </View>
                                    <Ionicons
                                        name={isExpanded ? 'chevron-up' : 'chevron-down'}
                                        size={14}
                                        color={theme.colors.text.tertiary}
                                        style={{ marginLeft: 6 }}
                                    />
                                </View>

                                {/* Expanded: cost + earnings + round progression */}
                                {isExpanded && (
                                    <View variant="transparent" style={[styles.resultsExpanded, { borderColor: theme.colors.border.subtle }]}>
                                        <View variant="transparent" style={styles.resultRow}>
                                            <Text variant="caption" color="secondary" style={{ flex: 1 }}>Paid at auction</Text>
                                            <Text variant="caption" bold>{formatCurrency(item.winning_bid, market_type)}</Text>
                                        </View>
                                        {results
                                            .sort((a, b) => (a.round_number ?? 0) - (b.round_number ?? 0))
                                            .map(r => {
                                                const isAdvanced = r.result === 'advanced' || r.result === 'won';
                                                const rn = r.round_number ?? 0;
                                                const roundName = roundNameMap[rn] || `Round ${rn}`;
                                                return (
                                                    <View key={r.calcutta_item_result_id} variant="transparent" style={styles.resultRow}>
                                                        <Ionicons
                                                            name={isAdvanced ? 'checkmark-circle' : 'close-circle'}
                                                            size={14}
                                                            color={isAdvanced ? theme.colors.status.success : theme.colors.status.error}
                                                        />
                                                        <Text variant="caption" style={{ flex: 1, marginLeft: 6 }}>{roundName}</Text>
                                                        <Text variant="caption" color="secondary">{getStatusLabel(r.result)}</Text>
                                                        {Number(r.payout_earned) > 0 && (
                                                            <Text variant="caption" bold style={{ color: theme.colors.status.success, marginLeft: 8 }}>
                                                                +{formatCurrency(r.payout_earned, market_type)}
                                                            </Text>
                                                        )}
                                                    </View>
                                                );
                                            })}
                                        {results.length === 0 && (
                                            <Text variant="caption" color="tertiary" style={{ textAlign: 'center', paddingVertical: 4 }}>
                                                No round results yet
                                            </Text>
                                        )}
                                    </View>
                                )}
                            </TouchableOpacity>
                        );
                    }}
                />
            </View>
        );
    }

    // ============================================
    // AUCTIONING — "My Bids" bidding view
    // ============================================
    if (rows.length === 0) {
        return (
            <View variant="transparent" style={styles.container}>
                <>{listHeader}</>
                <View variant="transparent" style={styles.emptyContainer}>
                    <Ionicons name="pricetag-outline" size={40} color={theme.colors.text.tertiary} />
                    <Text variant="body" color="tertiary" style={{ marginTop: 12 }}>No bids yet</Text>
                    <Text variant="caption" color="tertiary" style={{ marginTop: 4, textAlign: 'center' }}>
                        Browse the Items tab to start bidding
                    </Text>
                </View>
            </View>
        );
    }

    return (
        <View variant="transparent" style={styles.container}>
            <FlatList
                data={rows}
                keyExtractor={r => r.bid.calcutta_bid_id}
                contentContainerStyle={styles.list}
                ListHeaderComponent={
                    <View variant="transparent">
                        <>{listHeader}</>
                        <View variant="transparent" style={[styles.summary, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                            <View variant="transparent" style={styles.summaryItem}>
                                <Text variant="caption" color="tertiary">Total Bids</Text>
                                <Text variant="body" bold>{activeBids.length}</Text>
                            </View>
                            <View variant="transparent" style={[styles.summaryItem, { borderLeftWidth: 1, borderColor: theme.colors.border.subtle }]}>
                                <Text variant="caption" color="tertiary">Committed</Text>
                                <Text variant="body" bold>{formatCurrency(totalCommitted, market_type)}</Text>
                            </View>
                            <View variant="transparent" style={[styles.summaryItem, { borderLeftWidth: 1, borderColor: theme.colors.border.subtle }]}>
                                <Text variant="caption" color="tertiary">Remaining</Text>
                                <Text variant="body" bold>{formatCurrency(budgetRemaining, market_type)}</Text>
                            </View>
                        </View>
                    </View>
                }
                renderItem={({ item: row }) => (
                    <View
                        variant="transparent"
                        style={[styles.bidCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}
                    >
                        <View variant="transparent" style={styles.bidRow}>
                            <View variant="transparent" style={{ flex: 1 }}>
                                <Text variant="body" bold numberOfLines={1}>
                                    {row.item?.item_name ?? 'Unknown Item'}
                                </Text>
                                <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginTop: 2 }}>
                                    <Ionicons
                                        name="ellipse"
                                        size={8}
                                        color={getBidStatusColor(row.bid.bid_status)}
                                    />
                                    <Text variant="caption" style={{ color: getBidStatusColor(row.bid.bid_status), marginLeft: 4, fontSize: 11, lineHeight: 15 }}>
                                        {getStatusLabel(row.bid.bid_status)}
                                    </Text>
                                </View>
                            </View>
                            <Text variant="h3" bold style={{ color: theme.colors.status.success }}>
                                {formatCurrency(row.bid.bid_amount, market_type)}
                            </Text>
                        </View>

                        {/* Actions — only when auctioning AND timer hasn't expired */}
                        {!auctionExpired ? (
                            <View variant="transparent" style={styles.actions}>
                                <TouchableOpacity
                                    style={[styles.actionBtn, { borderColor: theme.colors.border.subtle }]}
                                    onPress={() => onUpdateBid(row.bid.calcutta_auction_item_id)}
                                    activeOpacity={0.7}
                                >
                                    <Ionicons name="create-outline" size={14} color={theme.colors.primary.default} />
                                    <Text variant="caption" bold style={{ color: theme.colors.primary.default, marginLeft: 4 }}>
                                        Update
                                    </Text>
                                </TouchableOpacity>
                                <TouchableOpacity
                                    style={[styles.actionBtn, { borderColor: theme.colors.status.error + '40', marginLeft: 8 }]}
                                    onPress={() => onCancelBid(row.bid.calcutta_bid_id)}
                                    disabled={cancelLoading}
                                    activeOpacity={0.7}
                                >
                                    <Ionicons name="close-outline" size={14} color={theme.colors.status.error} />
                                    <Text variant="caption" bold style={{ color: theme.colors.status.error, marginLeft: 4 }}>
                                        Cancel
                                    </Text>
                                </TouchableOpacity>
                            </View>
                        ) : (
                            <View variant="transparent" style={[styles.expiredNotice, { backgroundColor: theme.colors.surface.base }]}>
                                <Ionicons name="time-outline" size={14} color={theme.colors.text.tertiary} />
                                <Text variant="caption" color="tertiary" style={{ marginLeft: 6 }}>
                                    Auction ended — resolving results...
                                </Text>
                            </View>
                        )}
                    </View>
                )}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    emptyContainer: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        padding: 40,
    },
    summary: {
        flexDirection: 'row',
        margin: 12,
        borderRadius: 10,
        borderWidth: 1,
        overflow: 'hidden',
    },
    summaryItem: {
        flex: 1,
        alignItems: 'center',
        paddingVertical: 12,
    },
    roiBanner: {
        marginHorizontal: 12,
        marginTop: 8,
        paddingVertical: 8,
        borderRadius: 8,
        alignItems: 'center',
    },
    sectionLabel: {
        paddingHorizontal: 16,
        paddingBottom: 8,
    },
    list: {
        paddingHorizontal: 12,
        paddingBottom: 40,
    },
    ownedCard: {
        borderWidth: 1,
        borderRadius: 10,
        marginBottom: 8,
        overflow: 'hidden',
    },
    ownedRow: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 12,
    },
    ownedIcon: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: 12,
    },
    ownedItemImage: {
        width: 40,
        height: 40,
        borderRadius: 20,
    },
    resultsExpanded: {
        borderTopWidth: 1,
        paddingHorizontal: 12,
        paddingVertical: 6,
    },
    resultRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 4,
    },
    bidCard: {
        borderWidth: 1,
        borderRadius: 10,
        padding: 12,
        marginBottom: 8,
    },
    bidRow: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    actions: {
        flexDirection: 'row',
        marginTop: 10,
    },
    actionBtn: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 12,
        paddingVertical: 6,
        borderRadius: 6,
        borderWidth: 1,
    },
    expiredNotice: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 10,
        paddingHorizontal: 10,
        paddingVertical: 8,
        borderRadius: 6,
    },
});
