import React from 'react';
import { StyleSheet, TouchableOpacity, Image, ScrollView, Share } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type {
    CalcuttaCompetitionProps,
    CalcuttaRoundProps,
    CalcuttaPayoutRuleProps,
    CalcuttaEscrowProps,
} from '@bettoredge/types';
import type { CalcuttaLifecycleState } from '../../helpers/lifecycleState';
import { canManageEscrow } from '../../helpers/lifecycleState';
import { formatCurrency } from '../../helpers/formatting';
import { CalcuttaEscrow } from '../CalcuttaEscrow';

interface SealedBidInfoTabProps {
    competition: CalcuttaCompetitionProps;
    rounds: CalcuttaRoundProps[];
    payout_rules: CalcuttaPayoutRuleProps[];
    escrow?: CalcuttaEscrowProps;
    market_type: string;
    player_balance?: number;
    onDepositFunds?: (amount: number) => void;
    onEscrowUpdate: () => void;
    lifecycleState: CalcuttaLifecycleState;
}

export const SealedBidInfoTab: React.FC<SealedBidInfoTabProps> = ({
    competition,
    rounds,
    payout_rules,
    escrow,
    market_type,
    player_balance,
    onDepositFunds,
    onEscrowUpdate,
    lifecycleState,
}) => {
    const { theme } = useTheme();
    const totalPot = Number(competition.total_pot) || 0;
    const escrowInteractive = canManageEscrow(lifecycleState);
    const showEscrow = lifecycleState !== 'pending';

    const handleCopyCode = () => {
        // Copy is handled by the share flow or parent component
    };

    const handleShare = async () => {
        try {
            const msg = competition.competition_code
                ? `Join my Calcutta auction "${competition.competition_name}"! Code: ${competition.competition_code}`
                : `Check out the Calcutta auction "${competition.competition_name}" on BettorEdge!`;
            await Share.share({ message: msg });
        } catch {}
    };

    return (
        <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
            {/* Hero image */}
            {competition.image?.url ? (
                <Image source={{ uri: competition.image.url }} style={styles.heroImage} resizeMode="cover" />
            ) : (
                <View variant="transparent" style={[styles.heroPlaceholder, { backgroundColor: theme.colors.surface.elevated }]}>
                    <Ionicons name="hammer-outline" size={48} color={theme.colors.text.tertiary} />
                </View>
            )}

            {/* Name + description */}
            <View variant="transparent" style={styles.section}>
                <Text variant="h3" bold>{competition.competition_name}</Text>
                {competition.competition_description ? (
                    <Text variant="body" color="secondary" style={{ marginTop: 6 }}>{competition.competition_description}</Text>
                ) : null}
            </View>

            {/* Payout structure */}
            {payout_rules.length > 0 && (
                <View variant="transparent" style={[styles.section, { borderColor: theme.colors.border.subtle }]}>
                    <Text variant="body" bold style={{ marginBottom: 8 }}>Payout Structure</Text>
                    {payout_rules.map((rule, i) => {
                        const round = rounds.find(r => r.round_number === rule.round_number);
                        const pct = Number(rule.payout_pct);
                        const amount = totalPot > 0 ? (pct / 100) * totalPot : 0;
                        return (
                            <View
                                key={rule.calcutta_payout_rule_id || `rule-${i}`}
                                variant="transparent"
                                style={[styles.payoutRow, i < payout_rules.length - 1 && { borderBottomWidth: 1, borderColor: theme.colors.border.subtle }]}
                            >
                                <Text variant="body" style={{ flex: 1 }}>
                                    {rule.description || round?.round_name || `Round ${rule.round_number}`}
                                </Text>
                                <Text variant="body" bold>{pct}%</Text>
                                {totalPot > 0 && (
                                    <Text variant="caption" color="tertiary" style={{ marginLeft: 8, minWidth: 60, textAlign: 'right' }}>
                                        {formatCurrency(amount, market_type)}
                                    </Text>
                                )}
                            </View>
                        );
                    })}
                </View>
            )}

            {/* Rules card */}
            {(competition.min_bid > 0 || competition.bid_increment > 0 || competition.max_escrow || competition.min_spend_pct) && (
                <View variant="transparent" style={[styles.rulesCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                    <Text variant="body" bold style={{ marginBottom: 8 }}>Rules</Text>
                    {competition.min_bid > 0 && (
                        <Text variant="caption" color="secondary" style={styles.ruleItem}>
                            Min Bid: {formatCurrency(competition.min_bid, market_type)}
                        </Text>
                    )}
                    {competition.bid_increment > 0 && (
                        <Text variant="caption" color="secondary" style={styles.ruleItem}>
                            Bid Increment: {formatCurrency(competition.bid_increment, market_type)}
                        </Text>
                    )}
                    {competition.max_escrow != null && Number(competition.max_escrow) > 0 && (
                        <Text variant="caption" color="secondary" style={styles.ruleItem}>
                            Budget Cap: {formatCurrency(Number(competition.max_escrow), market_type)}
                        </Text>
                    )}
                    {competition.min_spend_pct != null && Number(competition.min_spend_pct) > 0 && (
                        <Text variant="caption" color="secondary" style={styles.ruleItem}>
                            Min Spend: {competition.min_spend_pct}% of deposited funds
                        </Text>
                    )}
                </View>
            )}

            {/* Rounds */}
            {rounds.length > 0 && (
                <View variant="transparent" style={[styles.section, { borderColor: theme.colors.border.subtle }]}>
                    <Text variant="body" bold style={{ marginBottom: 8 }}>Rounds</Text>
                    {rounds.map(r => (
                        <View key={r.calcutta_round_id} variant="transparent" style={styles.roundRow}>
                            <Text variant="caption" color="tertiary" style={{ minWidth: 20 }}>{r.round_number}</Text>
                            <Text variant="body" style={{ marginLeft: 8 }}>{r.round_name}</Text>
                        </View>
                    ))}
                </View>
            )}

            {/* Competition code */}
            {competition.competition_code && (
                <View variant="transparent" style={styles.section}>
                    <TouchableOpacity
                        onPress={handleCopyCode}
                        style={[styles.codeRow, { backgroundColor: theme.colors.primary.subtle }]}
                        activeOpacity={0.7}
                    >
                        <Ionicons name="key-outline" size={14} color={theme.colors.primary.default} />
                        <Text variant="body" bold style={{ color: theme.colors.primary.default, marginLeft: 6, flex: 1 }}>
                            {competition.competition_code}
                        </Text>
                        <Ionicons name="copy-outline" size={16} color={theme.colors.primary.default} />
                    </TouchableOpacity>
                </View>
            )}

            {/* Share button */}
            <View variant="transparent" style={styles.section}>
                <TouchableOpacity
                    onPress={handleShare}
                    style={[styles.shareBtn, { borderColor: theme.colors.border.subtle }]}
                    activeOpacity={0.7}
                >
                    <Ionicons name="share-outline" size={16} color={theme.colors.text.secondary} />
                    <Text variant="caption" bold color="secondary" style={{ marginLeft: 6 }}>Share</Text>
                </TouchableOpacity>
            </View>

            {/* Escrow management — hidden in pending, read-only in tournament/completed */}
            {showEscrow && (
                <View variant="transparent" style={[styles.section, { borderColor: theme.colors.border.subtle }]}>
                    <Text variant="body" bold style={{ marginBottom: 8 }}>Escrow</Text>
                    <CalcuttaEscrow
                        calcutta_competition_id={competition.calcutta_competition_id}
                        escrow={escrow}
                        market_type={market_type}
                        max_escrow={competition.max_escrow}
                        player_balance={player_balance}
                        onDepositFunds={onDepositFunds}
                        onUpdate={onEscrowUpdate}
                        readOnly={!escrowInteractive}
                    />
                </View>
            )}
        </ScrollView>
    );
};

const styles = StyleSheet.create({
    content: {
        paddingBottom: 60,
    },
    heroImage: {
        width: '100%',
        height: 180,
    },
    heroPlaceholder: {
        width: '100%',
        height: 120,
        alignItems: 'center',
        justifyContent: 'center',
    },
    section: {
        padding: 16,
        borderTopWidth: 1,
    },
    payoutRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 10,
    },
    rulesCard: {
        margin: 16,
        marginTop: 0,
        padding: 14,
        borderRadius: 10,
        borderWidth: 1,
    },
    ruleItem: {
        marginBottom: 4,
    },
    roundRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 6,
    },
    codeRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 14,
        paddingVertical: 10,
        borderRadius: 10,
    },
    shareBtn: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        paddingVertical: 10,
        borderRadius: 10,
        borderWidth: 1,
    },
});
