import React, { useEffect, useState, useRef } from 'react';
import { StyleSheet, Animated, Dimensions } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type { CalcuttaAuctionItemProps } from '@bettoredge/types';

export interface AuctionCountdownOverlayProps {
    visible: boolean;
    competitionName?: string;
    firstItem?: CalcuttaAuctionItemProps;
    countdownFrom?: number;
    onComplete: () => void;
}

export const AuctionCountdownOverlay: React.FC<AuctionCountdownOverlayProps> = ({
    visible,
    competitionName,
    firstItem,
    countdownFrom = 5,
    onComplete,
}) => {
    const { theme } = useTheme();
    const [count, setCount] = useState(countdownFrom);
    const scaleAnim = useRef(new Animated.Value(1)).current;
    const opacityAnim = useRef(new Animated.Value(0)).current;
    const numberScale = useRef(new Animated.Value(0.5)).current;

    useEffect(() => {
        if (!visible) {
            setCount(countdownFrom);
            opacityAnim.setValue(0);
            return;
        }

        // Fade in
        Animated.timing(opacityAnim, {
            toValue: 1,
            duration: 300,
            useNativeDriver: true,
        }).start();

        setCount(countdownFrom);
    }, [visible]);

    // Countdown tick
    useEffect(() => {
        if (!visible) return;
        if (count <= 0) {
            // Fade out then complete
            Animated.timing(opacityAnim, {
                toValue: 0,
                duration: 400,
                useNativeDriver: true,
            }).start(() => onComplete());
            return;
        }

        // Pop animation for each number
        numberScale.setValue(0.3);
        Animated.spring(numberScale, {
            toValue: 1,
            friction: 4,
            tension: 100,
            useNativeDriver: true,
        }).start();

        const timer = setTimeout(() => setCount(c => c - 1), 1000);
        return () => clearTimeout(timer);
    }, [count, visible]);

    if (!visible) return null;


    return (
        <Animated.View style={[styles.overlay, { opacity: opacityAnim }]}>
            <View variant="transparent" style={styles.backdrop} />
            <View variant="transparent" style={styles.content}>
                {/* Competition name */}
                <Text variant="caption" bold style={styles.label}>
                    {competitionName || 'Auction'}
                </Text>

                {/* Status text */}
                <Text variant="body" style={styles.subtitle}>
                    {count > 0 ? 'Starting in' : 'GO!'}
                </Text>

                {/* Big countdown number */}
                {count > 0 && (
                    <Animated.View style={{ transform: [{ scale: numberScale }] }}>
                        <Text style={[styles.countNumber, { color: count <= 3 ? '#EF4444' : '#FFFFFF' }]}>
                            {count}
                        </Text>
                    </Animated.View>
                )}

                {count <= 0 && (
                    <Animated.View style={{ transform: [{ scale: numberScale }] }}>
                        <Ionicons name="flash" size={80} color="#F59E0B" />
                    </Animated.View>
                )}

                {/* First item preview */}
                {firstItem && (
                    <View variant="transparent" style={styles.itemPreview}>
                        <Text variant="caption" style={styles.itemLabel}>First up</Text>
                        <Text variant="h3" bold style={styles.itemName}>{firstItem.item_name}</Text>
                        {firstItem.seed != null && (
                            <Text variant="caption" style={styles.itemSeed}>Seed #{firstItem.seed}</Text>
                        )}
                    </View>
                )}
            </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)',
    },
    content: {
        alignItems: 'center',
        justifyContent: 'center',
        padding: 40,
    },
    label: {
        color: 'rgba(255,255,255,0.6)',
        fontSize: 14,
        lineHeight: 19,
        letterSpacing: 2,
        textTransform: 'uppercase',
        marginBottom: 8,
    },
    subtitle: {
        color: 'rgba(255,255,255,0.8)',
        fontSize: 18,
        lineHeight: 24,
        marginBottom: 16,
    },
    countNumber: {
        fontSize: 120,
        fontWeight: '900',
        lineHeight: 156,
    },
    itemPreview: {
        marginTop: 40,
        alignItems: 'center',
        backgroundColor: 'rgba(255,255,255,0.1)',
        paddingHorizontal: 30,
        paddingVertical: 16,
        borderRadius: 16,
    },
    itemLabel: {
        color: 'rgba(255,255,255,0.5)',
        fontSize: 12,
        lineHeight: 16,
        textTransform: 'uppercase',
        letterSpacing: 1,
    },
    itemName: {
        color: '#FFFFFF',
        fontSize: 22,
        lineHeight: 29,
        marginTop: 4,
    },
    itemSeed: {
        color: 'rgba(255,255,255,0.5)',
        marginTop: 2,
    },
});
