import React, { useEffect, useRef, useMemo, useState } from 'react';
import { StyleSheet, Animated, TouchableOpacity, ScrollView, useWindowDimensions, NativeSyntheticEvent, NativeScrollEvent } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';

export interface CalcuttaWalkthroughProps {
    visible: boolean;
    onClose: () => void;
    auction_type: 'live' | 'sealed_bid' | 'sweepstakes';
}

interface SlideData {
    icon: string;
    iconColor: string;
    title: string;
    body: string;
    bullets?: string[];
}

const SLIDE_WHAT: SlideData = {
    icon: 'trophy-outline',
    iconColor: '#F59E0B',
    title: 'What is a Calcutta?',
    body: 'A Calcutta is a group auction pool. Players bid on teams or athletes in an auction. All winning bids form the prize pot. As your teams advance through tournament rounds, you earn payouts from the pot.',
};

const SLIDE_AUCTION: Record<string, SlideData> = {
    live: {
        icon: 'flash-outline',
        iconColor: '#3B82F6',
        title: 'Live Auction',
        body: 'Items are auctioned one at a time with a countdown timer. Place your bid before time runs out \u2014 highest bid wins!',
        bullets: [
            'Each item has its own timer',
            'Timer extends if a bid comes in near the end',
            'Stay sharp and watch for outbid alerts',
        ],
    },
    sealed_bid: {
        icon: 'lock-closed-outline',
        iconColor: '#8B5CF6',
        title: 'Sealed Bid Auction',
        body: 'Place hidden bids on any item before the deadline. No one sees your bid until bidding closes.',
        bullets: [
            'Bid on as many items as you want',
            'Highest bid on each item wins',
            'Results revealed when the auction ends',
        ],
    },
    sweepstakes: {
        icon: 'shuffle-outline',
        iconColor: '#10B981',
        title: 'Sweepstakes Draw',
        body: 'No bidding required! When the host starts the competition, teams are randomly assigned to players.',
        bullets: [
            'Just join and wait for the draw',
            'Every player gets a team',
            'Root for your team to advance!',
        ],
    },
};

const SLIDE_ESCROW: SlideData = {
    icon: 'wallet-outline',
    iconColor: '#10B981',
    title: 'Escrow & Funding',
    body: 'Before bidding, deposit funds into your escrow balance. This is your bidding budget so you don\u2019t hit your wallet on every bid.',
    bullets: [
        'When you bid, funds move from \u201Cavailable\u201D to \u201Ccommitted\u201D',
        'If you\u2019re outbid, funds return to available',
        'After the auction, unused escrow is returned to your wallet',
    ],
};

const SLIDE_PAYOUT: SlideData = {
    icon: 'cash-outline',
    iconColor: '#F59E0B',
    title: 'How You Get Paid',
    body: 'All winning bids form the prize pot. Each round of the tournament has a percentage of the pot allocated as payouts.',
    bullets: [
        'Teams that advance earn you payouts each round',
        'Eliminated teams\u2019 share goes to advancing owners',
        'Final round pays the biggest percentage',
    ],
};

export const CalcuttaWalkthrough: React.FC<CalcuttaWalkthroughProps> = ({
    visible,
    onClose,
    auction_type,
}) => {
    const { theme } = useTheme();
    const { width: windowWidth } = useWindowDimensions();
    const scrollRef = useRef<ScrollView>(null);
    const [currentSlide, setCurrentSlide] = useState(0);

    // Animations
    const opacityAnim = useRef(new Animated.Value(0)).current;
    const scaleAnim = useRef(new Animated.Value(0.85)).current;
    const iconScales = useRef([
        new Animated.Value(0),
        new Animated.Value(0),
        new Animated.Value(0),
        new Animated.Value(0),
    ]).current;

    const slides = useMemo(() => {
        const s: SlideData[] = [SLIDE_WHAT];
        s.push(SLIDE_AUCTION[auction_type] || SLIDE_AUCTION.live);
        if (auction_type !== 'sweepstakes') {
            s.push(SLIDE_ESCROW);
        }
        s.push(SLIDE_PAYOUT);
        return s;
    }, [auction_type]);

    const cardWidth = Math.min(windowWidth * 0.9, 420);
    const slideContentWidth = cardWidth - 56; // card padding 28 * 2

    useEffect(() => {
        if (!visible) {
            Animated.timing(opacityAnim, { toValue: 0, duration: 250, useNativeDriver: true }).start();
            return;
        }

        setCurrentSlide(0);
        scrollRef.current?.scrollTo({ x: 0, animated: false });

        opacityAnim.setValue(0);
        scaleAnim.setValue(0.85);
        iconScales.forEach(s => s.setValue(0));

        Animated.parallel([
            Animated.timing(opacityAnim, { toValue: 1, duration: 300, useNativeDriver: true }),
            Animated.spring(scaleAnim, { toValue: 1, friction: 6, tension: 80, useNativeDriver: true }),
        ]).start(() => {
            animateIcon(0);
        });
    }, [visible]);

    const animateIcon = (index: number) => {
        iconScales[index]?.setValue(0);
        Animated.spring(iconScales[index], {
            toValue: 1,
            friction: 4,
            tension: 100,
            useNativeDriver: true,
        }).start();
    };

    const goToSlide = (index: number) => {
        scrollRef.current?.scrollTo({ x: index * slideContentWidth, animated: true });
        setCurrentSlide(index);
        animateIcon(index);
    };

    const handleNext = () => {
        if (currentSlide < slides.length - 1) {
            goToSlide(currentSlide + 1);
        } else {
            onClose();
        }
    };

    const handleScrollEnd = (e: NativeSyntheticEvent<NativeScrollEvent>) => {
        const newIndex = Math.round(e.nativeEvent.contentOffset.x / slideContentWidth);
        if (newIndex !== currentSlide && newIndex >= 0 && newIndex < slides.length) {
            setCurrentSlide(newIndex);
            animateIcon(newIndex);
        }
    };

    if (!visible) return null;

    const isLastSlide = currentSlide === slides.length - 1;

    return (
        <Animated.View style={[styles.overlay, { opacity: opacityAnim }]}>
            <View variant="transparent" style={styles.backdrop} />
            <Animated.View style={[styles.card, { width: cardWidth, transform: [{ scale: scaleAnim }] }]}>

                {/* Slide content */}
                <ScrollView
                    ref={scrollRef}
                    horizontal
                    pagingEnabled
                    showsHorizontalScrollIndicator={false}
                    scrollEventThrottle={16}
                    onMomentumScrollEnd={handleScrollEnd}
                    style={{ width: slideContentWidth }}
                    contentContainerStyle={{ width: slideContentWidth * slides.length }}
                >
                    {slides.map((slide, i) => (
                        <View key={i} variant="transparent" style={[styles.slide, { width: slideContentWidth }]}>
                            {/* Icon circle */}
                            <Animated.View style={{ transform: [{ scale: iconScales[i] || new Animated.Value(1) }] }}>
                                <View variant="transparent" style={[styles.iconCircle, { backgroundColor: slide.iconColor + '20' }]}>
                                    <Ionicons name={slide.icon as any} size={40} color={slide.iconColor} />
                                </View>
                            </Animated.View>

                            {/* Title */}
                            <Text style={styles.title}>{slide.title}</Text>

                            {/* Body */}
                            <Text style={styles.body}>{slide.body}</Text>

                            {/* Bullets */}
                            {slide.bullets?.map((bullet, j) => (
                                <View key={j} variant="transparent" style={styles.bulletRow}>
                                    <View variant="transparent" style={[styles.bulletDot, { backgroundColor: slide.iconColor }]} />
                                    <Text style={styles.bulletText}>{bullet}</Text>
                                </View>
                            ))}
                        </View>
                    ))}
                </ScrollView>

                {/* Bottom navigation */}
                <View variant="transparent" style={styles.bottomBar}>
                    {/* Skip */}
                    {!isLastSlide ? (
                        <TouchableOpacity onPress={onClose} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
                            <Text style={styles.skipText}>Skip</Text>
                        </TouchableOpacity>
                    ) : (
                        <View variant="transparent" style={{ width: 40 }} />
                    )}

                    {/* Dots */}
                    <View variant="transparent" style={styles.dotsRow}>
                        {slides.map((_, i) => (
                            <View
                                key={i}
                                variant="transparent"
                                style={[
                                    styles.dot,
                                    i === currentSlide
                                        ? { backgroundColor: slides[currentSlide].iconColor, width: 20 }
                                        : { backgroundColor: 'rgba(255,255,255,0.3)' },
                                ]}
                            />
                        ))}
                    </View>

                    {/* Next / Get Started */}
                    <TouchableOpacity
                        onPress={handleNext}
                        style={[styles.nextButton, { backgroundColor: slides[currentSlide].iconColor }]}
                        activeOpacity={0.8}
                    >
                        {isLastSlide ? (
                            <Text style={styles.nextButtonText}>Let's Go</Text>
                        ) : (
                            <Ionicons name="arrow-forward" size={18} color="#FFF" />
                        )}
                    </TouchableOpacity>
                </View>
            </Animated.View>
        </Animated.View>
    );
};

const styles = StyleSheet.create({
    overlay: {
        ...StyleSheet.absoluteFillObject,
        zIndex: 999,
        alignItems: 'center',
        justifyContent: 'center',
    },
    backdrop: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: 'rgba(0,0,0,0.85)',
    },
    card: {
        backgroundColor: '#1a1a2e',
        borderRadius: 24,
        padding: 28,
        alignItems: 'center',
        maxWidth: 420,
        overflow: 'hidden',
    },
    slide: {
        alignItems: 'center',
        paddingTop: 8,
        paddingBottom: 16,
    },
    iconCircle: {
        width: 80,
        height: 80,
        borderRadius: 40,
        alignItems: 'center',
        justifyContent: 'center',
        marginBottom: 20,
    },
    title: {
        color: '#FFFFFF',
        fontSize: 22,
        lineHeight: 28,
        fontWeight: '800',
        textAlign: 'center',
        marginBottom: 12,
    },
    body: {
        color: 'rgba(255,255,255,0.75)',
        fontSize: 15,
        lineHeight: 22,
        textAlign: 'center',
        marginBottom: 16,
    },
    bulletRow: {
        flexDirection: 'row',
        alignItems: 'flex-start',
        width: '100%',
        paddingHorizontal: 4,
        marginBottom: 8,
    },
    bulletDot: {
        width: 6,
        height: 6,
        borderRadius: 3,
        marginTop: 7,
        marginRight: 10,
    },
    bulletText: {
        color: 'rgba(255,255,255,0.65)',
        fontSize: 14,
        lineHeight: 20,
        flex: 1,
    },
    bottomBar: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        width: '100%',
        marginTop: 8,
        paddingTop: 16,
        borderTopWidth: 1,
        borderTopColor: 'rgba(255,255,255,0.08)',
    },
    skipText: {
        color: 'rgba(255,255,255,0.4)',
        fontSize: 14,
        lineHeight: 19,
        fontWeight: '600',
    },
    dotsRow: {
        flexDirection: 'row',
        alignItems: 'center',
        gap: 6,
    },
    dot: {
        width: 8,
        height: 8,
        borderRadius: 4,
    },
    nextButton: {
        paddingHorizontal: 16,
        paddingVertical: 8,
        borderRadius: 20,
        alignItems: 'center',
        justifyContent: 'center',
        minWidth: 40,
    },
    nextButtonText: {
        color: '#FFFFFF',
        fontSize: 14,
        lineHeight: 19,
        fontWeight: '700',
    },
});
