import React, { useState } from 'react';
import { StyleSheet, TouchableOpacity, ScrollView } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type {
    CalcuttaRoundProps,
    CalcuttaAuctionItemProps,
    CalcuttaItemResultProps,
    CalcuttaPayoutRuleProps,
} from '@bettoredge/types';
import { useCalcuttaResults, RoundResultSummary } from '../hooks/useCalcuttaResults';
import { formatCurrency, getStatusLabel } from '../helpers/formatting';

export interface CalcuttaRoundResultsProps {
    rounds: CalcuttaRoundProps[];
    items: CalcuttaAuctionItemProps[];
    item_results: CalcuttaItemResultProps[];
    payout_rules: CalcuttaPayoutRuleProps[];
    market_type: string;
    total_pot?: number;
    unclaimed_pot?: number;
    auction_type?: string;
}

export const CalcuttaRoundResults: React.FC<CalcuttaRoundResultsProps> = ({
    rounds,
    items,
    item_results,
    payout_rules,
    market_type,
    total_pot,
    unclaimed_pot,
    auction_type,
}) => {
    const isSweepstakes = auction_type === 'sweepstakes';
    const { theme } = useTheme();
    const { roundSummaries } = useCalcuttaResults(rounds, items, item_results, payout_rules);
    const [expandedRound, setExpandedRound] = useState<string | null>(null);

    if (rounds.length === 0) {
        return (
            <View variant="transparent" style={styles.emptyContainer}>
                <Text variant="caption" color="tertiary">No rounds yet</Text>
            </View>
        );
    }

    const toggleRound = (roundId: string) => {
        setExpandedRound(prev => prev === roundId ? null : roundId);
    };

    const renderRound = (summary: RoundResultSummary) => {
        const isExpanded = expandedRound === summary.round.calcutta_round_id;
        const statusColor = summary.round.status === 'closed'
            ? theme.colors.status.success
            : summary.round.status === 'inprogress'
                ? theme.colors.primary.default
                : theme.colors.text.tertiary;

        return (
            <View
                key={summary.round.calcutta_round_id}
                variant="transparent"
                style={[styles.roundCard, { borderColor: theme.colors.border.subtle }]}
            >
                <TouchableOpacity
                    style={styles.roundHeader}
                    onPress={() => toggleRound(summary.round.calcutta_round_id)}
                    activeOpacity={0.7}
                >
                    <View variant="transparent" style={styles.roundInfo}>
                        <Text variant="body" bold>{summary.round.round_name}</Text>
                        <View variant="transparent" style={styles.roundMeta}>
                            <View variant="transparent" style={[styles.statusDot, { backgroundColor: statusColor }]} />
                            <Text variant="caption" color="tertiary">
                                {getStatusLabel(summary.round.status)}
                            </Text>
                            {!isSweepstakes && summary.total_payout > 0 && (
                                <Text variant="caption" style={{ color: theme.colors.status.success, marginLeft: 8 }}>
                                    {formatCurrency(summary.total_payout, market_type)} paid
                                </Text>
                            )}
                            {isSweepstakes && summary.round.prize_description && (
                                <Text variant="caption" style={{ color: theme.colors.primary.default, marginLeft: 8 }} numberOfLines={1}>
                                    Prize available
                                </Text>
                            )}
                        </View>
                    </View>
                    <View variant="transparent" style={styles.roundCounts}>
                        <Text variant="caption" bold style={{ color: theme.colors.status.success }}>
                            {summary.advanced_items.length}/{summary.advanced_items.length + summary.eliminated_items.length}
                        </Text>
                        <Text variant="caption" color="tertiary" style={{ marginLeft: 4 }}>advanced</Text>
                    </View>
                    <Ionicons
                        name={isExpanded ? 'chevron-up' : 'chevron-down'}
                        size={16}
                        color={theme.colors.text.tertiary}
                        style={styles.chevron}
                    />
                </TouchableOpacity>

                {isExpanded && (
                    <View variant="transparent" style={[styles.roundBody, { borderColor: theme.colors.border.subtle }]}>
                        {/* Sweepstakes: show prize instead of payout rule */}
                        {isSweepstakes && summary.round.prize_description && (
                            <View variant="transparent" style={styles.payoutRow}>
                                <Ionicons name="gift-outline" size={14} color={theme.colors.primary.default} />
                                <Text variant="caption" style={{ marginLeft: 6, color: theme.colors.primary.default, flex: 1 }}>
                                    Prize: {summary.round.prize_description}
                                </Text>
                            </View>
                        )}

                        {/* Payout rule (non-sweepstakes) */}
                        {!isSweepstakes && summary.payout_rule && (
                            <View variant="transparent" style={styles.payoutRow}>
                                <Ionicons name="cash-outline" size={14} color={theme.colors.text.tertiary} />
                                <Text variant="caption" color="tertiary" style={{ marginLeft: 6 }}>
                                    {summary.payout_rule.payout_pct}% of pot split among advancing teams
                                </Text>
                            </View>
                        )}

                        {/* Rollover notice for unsold advancing items (non-sweepstakes) */}
                        {!isSweepstakes && summary.round.status === 'closed' && summary.advanced_items.some(i => !i.winning_player_id) && (
                            <View variant="transparent" style={[styles.payoutRow, { marginTop: 2 }]}>
                                <Ionicons name="arrow-forward-circle-outline" size={14} color={theme.colors.primary.default} />
                                <Text variant="caption" style={{ marginLeft: 6, color: theme.colors.primary.default, flex: 1 }}>
                                    Unbid teams' share rolls into the next round. Any amount remaining after the final round is redistributed to all players proportionally.
                                </Text>
                            </View>
                        )}

                        {/* Advanced items */}
                        {summary.advanced_items.length > 0 && (
                            <>
                                <Text variant="caption" bold color="secondary" style={styles.sectionLabel}>
                                    Advanced ({summary.advanced_items.length})
                                </Text>
                                {summary.advanced_items.map(item => {
                                    const isUnsold = !item.winning_player_id;
                                    return (
                                        <View key={item.calcutta_auction_item_id} variant="transparent" style={styles.itemRow}>
                                            <Ionicons
                                                name={isUnsold ? 'help-circle' : 'checkmark-circle'}
                                                size={14}
                                                color={isUnsold ? theme.colors.text.tertiary : theme.colors.status.success}
                                            />
                                            <Text variant="caption" style={[styles.itemName, isUnsold && { color: theme.colors.text.tertiary }]} numberOfLines={1}>
                                                {item.item_name}{isUnsold ? ' (unbid)' : ''}
                                            </Text>
                                            {item.seed != null && (
                                                <Text variant="caption" color="tertiary">#{item.seed}</Text>
                                            )}
                                        </View>
                                    );
                                })}
                            </>
                        )}

                        {/* Eliminated items */}
                        {summary.eliminated_items.length > 0 && (
                            <>
                                <Text variant="caption" bold color="secondary" style={styles.sectionLabel}>
                                    Eliminated ({summary.eliminated_items.length})
                                </Text>
                                {summary.eliminated_items.map(item => {
                                    const isUnsold = !item.winning_player_id;
                                    return (
                                        <View key={item.calcutta_auction_item_id} variant="transparent" style={styles.itemRow}>
                                            <Ionicons name="close-circle" size={14} color={theme.colors.status.error} />
                                            <Text variant="caption" style={[styles.itemName, isUnsold && { color: theme.colors.text.tertiary }]} numberOfLines={1}>
                                                {item.item_name}{isUnsold ? ' (unbid)' : ''}
                                            </Text>
                                            {item.seed != null && (
                                                <Text variant="caption" color="tertiary">#{item.seed}</Text>
                                            )}
                                        </View>
                                    );
                                })}
                            </>
                        )}

                        {summary.advanced_items.length === 0 && summary.eliminated_items.length === 0 && (
                            <Text variant="caption" color="tertiary" style={styles.noResults}>
                                No results yet for this round
                            </Text>
                        )}
                    </View>
                )}
            </View>
        );
    };

    return (
        <ScrollView style={styles.container}>
            {roundSummaries.map(renderRound)}
        </ScrollView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    emptyContainer: {
        alignItems: 'center',
        padding: 20,
    },
    roundCard: {
        borderBottomWidth: 1,
    },
    roundHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 12,
    },
    roundInfo: {
        flex: 1,
    },
    roundMeta: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 4,
    },
    statusDot: {
        width: 6,
        height: 6,
        borderRadius: 3,
        marginRight: 6,
    },
    roundCounts: {
        marginHorizontal: 10,
    },
    chevron: {
        marginLeft: 4,
    },
    roundBody: {
        paddingHorizontal: 12,
        paddingBottom: 12,
        borderTopWidth: 1,
    },
    payoutRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 8,
    },
    sectionLabel: {
        marginTop: 8,
        marginBottom: 4,
    },
    itemRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 4,
        paddingLeft: 4,
    },
    itemName: {
        flex: 1,
        marginLeft: 6,
    },
    noResults: {
        paddingVertical: 8,
        textAlign: 'center',
    },
});
