import { Images } from '@/constants/images';
import Service from '@/services/dimension';
import { ImageBackground } from 'expo-image';
import React, { forwardRef, useImperativeHandle, useState } from 'react';
import { FlatList, Image, Modal, StyleSheet, Text, TouchableOpacity, View } from 'react-native';

export interface WinRecordModalRef {
    show: () => void;
    close: () => void;
}

export const WinRecordModal = forwardRef<WinRecordModalRef>((_, ref) => {
    const [visible, setVisible] = useState(false);
    const [data, setData] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const [current, setCurrent] = useState(1);
    const size = 20;
    const [hasMore, setHasMore] = useState(true);

    useImperativeHandle(ref, () => ({
        show: () => {
            setVisible(true);
            refresh();
        },
        close: () => setVisible(false),
    }));

    const getData = async (pageNum: number, isRefresh: boolean = false) => {
        if (loading) return;
        setLoading(true);
        try {
            const res = await Service.prizeResult({ current: pageNum, size });
            if (res && res.records) {
                if (isRefresh) {
                    setData(res.records);
                } else {
                    setData(prev => [...prev, ...res.records]);
                }
                if (res.records.length < size) {
                    setHasMore(false);
                } else {
                    setHasMore(true);
                }
            }
        } catch (error) {
            console.error("Failed to fetch records", error);
        } finally {
            setLoading(false);
            setIsRefreshing(false);
        }
    };

    const refresh = () => {
        setCurrent(1);
        setIsRefreshing(true);
        setHasMore(true);
        getData(1, true);
    };

    const loadMore = () => {
        if (!loading && hasMore) {
            const next = current + 1;
            setCurrent(next);
            getData(next);
        }
    };

    if (!visible) return null;

    return (
        <Modal visible={visible} transparent animationType="fade" onRequestClose={() => setVisible(false)}>
            <View style={styles.overlay}>
                <View style={styles.contentContainer}>
                    <ImageBackground source={{ uri: Images.mine.dialogContentBg }} style={styles.contentBg} resizeMode="stretch">
                        <TouchableOpacity onPress={() => setVisible(false)} style={styles.closeBtn}>
                            <Image source={{ uri: Images.common.closeBut }} style={styles.closeIcon} />
                        </TouchableOpacity>

                        <View style={styles.titleBox}>
                            <Text style={styles.title}>中奖记录</Text>
                        </View>

                        <View style={styles.listBox}>
                            {data.length > 0 ? (
                                <FlatList
                                    data={data}
                                    keyExtractor={(item, index) => index.toString()}
                                    renderItem={({ item }) => (
                                        <View style={styles.item}>
                                            <Image source={{ uri: item.cover }} style={styles.itemImg} />
                                            <Text style={styles.itemName} numberOfLines={1}>{item.name}</Text>
                                            <View style={styles.userInfo}>
                                                <ImageBackground source={{ uri: Images.common.indexBg }} style={styles.avatarBg} resizeMode="cover">
                                                    <Image source={{ uri: item.avatar || Images.common.defaultAvatar }} style={styles.avatar} />
                                                </ImageBackground>
                                                <Text style={styles.nickname} numberOfLines={1}>{item.nickname}</Text>
                                            </View>
                                        </View>
                                    )}
                                    onEndReached={loadMore}
                                    onEndReachedThreshold={0.1}
                                    refreshing={isRefreshing}
                                    onRefresh={refresh}
                                />
                            ) : (
                                <View style={styles.emptyContainer}>
                                    <Text style={styles.emptyText}>暂无记录</Text>
                                </View>
                            )}
                        </View>
                    </ImageBackground>
                </View>
            </View>
        </Modal>
    );
});

const styles = StyleSheet.create({
    overlay: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.6)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    contentContainer: {
        width: '100%',
        paddingHorizontal: 10,
        alignItems: 'center',
    },
    contentBg: {
        width: '100%', // Adjust based on your design, usually full width - padding
        height: 367, // 734rpx
        paddingTop: 69, // 138rpx
        position: 'relative',
    },
    closeBtn: {
        position: 'absolute',
        right: 15,
        top: 25,
        zIndex: 1,
    },
    closeIcon: {
        width: 30,
        height: 30,
    },
    titleBox: {
        position: 'absolute',
        top: 5,
        left: 0,
        right: 0,
        alignItems: 'center',
    },
    title: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#fff',
        marginTop: 28,
        textShadowColor: '#000',
        textShadowOffset: { width: 1, height: 1 },
        textShadowRadius: 1,
    },
    listBox: {
        flex: 1,
        paddingHorizontal: 20,
        paddingBottom: 20,
        marginTop: 20, // push down below header area
    },
    item: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#999',
    },
    itemImg: {
        width: 50, // 100rpx
        height: 50,
        borderRadius: 25,
        borderWidth: 2,
        borderColor: '#090909',
        marginRight: 10,
    },
    itemName: {
        fontSize: 12,
        color: '#000',
        fontWeight: 'bold',
        flex: 1,
        marginRight: 11,
    },
    userInfo: {
        width: 82, // 164rpx
        alignItems: 'flex-end',
    },
    avatarBg: {
        width: 32, // 64rpx
        height: 32,
        marginBottom: 5,
        justifyContent: 'center',
        alignItems: 'center',
    },
    avatar: {
        width: 32,
        height: 32,
        borderRadius: 16,
    },
    nickname: {
        fontSize: 10, // font2
        color: '#666',
    },
    emptyContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    emptyText: {
        color: '#999',
    }
});
