import React from 'react';
import { StyleSheet, FlatList, Image } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type { CalcuttaPayoutRuleProps, CalcuttaRoundProps } from '@bettoredge/types';
import { formatCurrency } from '../helpers/formatting';

export interface CalcuttaPayoutPreviewProps {
    payout_rules: CalcuttaPayoutRuleProps[];
    total_pot: number;
    market_type: string;
    unclaimed_pot?: number;
    min_spend_pct?: number;
    auction_type?: string;
    rounds?: CalcuttaRoundProps[];
}

export const CalcuttaPayoutPreview: React.FC<CalcuttaPayoutPreviewProps> = ({
    payout_rules,
    total_pot,
    market_type,
    unclaimed_pot,
    min_spend_pct,
    auction_type,
    rounds,
}) => {
    const { theme } = useTheme();
    const isSweepstakes = auction_type === 'sweepstakes';

    // Sweepstakes: render prize list per round instead of percentages
    if (isSweepstakes && rounds) {
        const prizeRounds = rounds.filter(r => r.prize_description);
        if (prizeRounds.length === 0) {
            return (
                <View variant="transparent" style={styles.container}>
                    <Text variant="caption" color="tertiary" style={styles.emptyText}>
                        No prizes defined
                    </Text>
                </View>
            );
        }
        return (
            <View variant="transparent" style={styles.container}>
                <View
                    variant="transparent"
                    style={[styles.potSummary, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}
                >
                    <Ionicons name="gift-outline" size={20} color={theme.colors.primary.default} />
                    <View variant="transparent" style={styles.potInfo}>
                        <Text variant="caption" color="tertiary">Prizes</Text>
                        <Text variant="body" bold>{prizeRounds.length} round{prizeRounds.length !== 1 ? 's' : ''}</Text>
                    </View>
                </View>
                {prizeRounds.map(round => (
                    <View
                        key={round.calcutta_round_id}
                        variant="transparent"
                        style={[styles.ruleRow, { borderColor: theme.colors.border.subtle }]}
                    >
                        {round.prize_image?.url && (
                            <Image
                                source={{ uri: round.prize_image.url }}
                                style={{ width: 36, height: 36, borderRadius: 6, marginRight: 10 }}
                                resizeMode="cover"
                            />
                        )}
                        <View variant="transparent" style={styles.ruleInfo}>
                            <Text variant="body" numberOfLines={1}>{round.round_name}</Text>
                            <Text variant="caption" color="secondary">{round.prize_description}</Text>
                        </View>
                    </View>
                ))}
            </View>
        );
    }

    const roundRules = payout_rules
        .filter(r => r.payout_type === 'round')
        .sort((a, b) => (a.round_number ?? 0) - (b.round_number ?? 0));

    const placementRules = payout_rules
        .filter(r => r.payout_type === 'placement')
        .sort((a, b) => (a.placement ?? 0) - (b.placement ?? 0));

    const totalPct = payout_rules.reduce((sum, r) => sum + r.payout_pct, 0);

    const renderRule = (rule: CalcuttaPayoutRuleProps) => {
        const amount = (rule.payout_pct / 100) * total_pot;
        return (
            <View
                key={rule.calcutta_payout_rule_id}
                variant="transparent"
                style={[styles.ruleRow, { borderColor: theme.colors.border.subtle }]}
            >
                <View variant="transparent" style={styles.ruleInfo}>
                    <Text variant="body" numberOfLines={1}>
                        {rule.description ?? `${rule.payout_type === 'round' ? `Round ${rule.round_number}` : `${rule.placement}${getOrdinal(rule.placement ?? 0)} Place`}`}
                    </Text>
                    <Text variant="caption" color="tertiary">
                        {rule.payout_type === 'round' ? 'Round Payout' : 'Placement Payout'}
                    </Text>
                </View>
                <View variant="transparent" style={styles.ruleAmounts}>
                    <Text variant="body" bold>
                        {formatCurrency(amount, market_type)}
                    </Text>
                    <Text variant="caption" color="tertiary">
                        {rule.payout_pct.toFixed(1)}%
                    </Text>
                </View>
            </View>
        );
    };

    return (
        <View variant="transparent" style={styles.container}>
            {/* Total pot summary */}
            <View
                variant="transparent"
                style={[styles.potSummary, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}
            >
                <Ionicons name="cash-outline" size={20} color={theme.colors.primary.default} />
                <View variant="transparent" style={styles.potInfo}>
                    <Text variant="caption" color="tertiary">Total Pot</Text>
                    <Text variant="body" bold>
                        {formatCurrency(total_pot, market_type)}
                    </Text>
                </View>
                <View variant="transparent" style={styles.potInfo}>
                    <Text variant="caption" color="tertiary">Allocated</Text>
                    <Text variant="body" bold>
                        {totalPct.toFixed(1)}%
                    </Text>
                </View>
            </View>

            {/* Min spend rule note */}
            {min_spend_pct != null && Number(min_spend_pct) > 0 && (
                <View
                    variant="transparent"
                    style={[styles.rolloverBanner, { backgroundColor: theme.colors.primary.subtle, borderColor: theme.colors.border.subtle }]}
                >
                    <Ionicons name="alert-circle-outline" size={16} color={theme.colors.primary.default} />
                    <View variant="transparent" style={{ marginLeft: 8, flex: 1 }}>
                        <Text variant="caption" style={{ color: theme.colors.text.secondary }}>
                            Min spend rule active: {Number(min_spend_pct)}%. If you deposit $300 but only bid $200, the ${((Number(min_spend_pct) / 100) * 300 - 200).toFixed(0)} shortfall is added to the pot.
                        </Text>
                    </View>
                </View>
            )}

            {/* Unclaimed rollover notice */}
            {(unclaimed_pot ?? 0) > 0 && (
                <View
                    variant="transparent"
                    style={[styles.rolloverBanner, { backgroundColor: theme.colors.primary.subtle, borderColor: theme.colors.border.subtle }]}
                >
                    <Ionicons name="swap-horizontal-outline" size={16} color={theme.colors.primary.default} />
                    <View variant="transparent" style={{ marginLeft: 8, flex: 1 }}>
                        <Text variant="caption" bold style={{ color: theme.colors.primary.default }}>
                            {formatCurrency(unclaimed_pot ?? 0, market_type)} rolling forward
                        </Text>
                        <Text variant="caption" style={{ color: theme.colors.text.secondary, marginTop: 2 }}>
                            From unbid teams that advanced. This amount is added to the next round's pool. After the final round, any remaining amount is split among all players based on how much they spent.
                        </Text>
                    </View>
                </View>
            )}

            {/* Round-based payouts */}
            {roundRules.length > 0 && (
                <>
                    <View variant="transparent" style={styles.sectionHeader}>
                        <Text variant="caption" bold color="secondary">Round Payouts</Text>
                    </View>
                    {roundRules.map(renderRule)}
                </>
            )}

            {/* Placement-based payouts */}
            {placementRules.length > 0 && (
                <>
                    <View variant="transparent" style={styles.sectionHeader}>
                        <Text variant="caption" bold color="secondary">Placement Payouts</Text>
                    </View>
                    {placementRules.map(renderRule)}
                </>
            )}

            {payout_rules.length === 0 && (
                <Text variant="caption" color="tertiary" style={styles.emptyText}>
                    No payout rules defined
                </Text>
            )}
        </View>
    );
};

const getOrdinal = (n: number): string => {
    const suffixes = ['th', 'st', 'nd', 'rd'];
    const v = n % 100;
    return (suffixes[(v - 20) % 10] || suffixes[v] || suffixes[0]);
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    potSummary: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 14,
        borderBottomWidth: 1,
    },
    potInfo: {
        marginLeft: 16,
    },
    sectionHeader: {
        paddingHorizontal: 12,
        paddingVertical: 8,
    },
    ruleRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 10,
        paddingHorizontal: 12,
        borderBottomWidth: 1,
    },
    ruleInfo: {
        flex: 1,
    },
    ruleAmounts: {
        alignItems: 'flex-end',
        marginLeft: 10,
    },
    emptyText: {
        textAlign: 'center',
        padding: 20,
    },
    rolloverBanner: {
        flexDirection: 'row',
        alignItems: 'flex-start',
        padding: 12,
        borderBottomWidth: 1,
    },
});
