import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import React, { useCallback, useEffect, useState } from 'react';
import {
    ActivityIndicator,
    FlatList,
    Image,
    ImageBackground,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { Images } from '@/constants/images';
import { getMyCreateList } from '@/services/dimension';

const CreateListScreen = () => {
    const router = useRouter();
    const insets = useSafeAreaInsets();
    const [list, setList] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [refreshing, setRefreshing] = useState(false);
    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);

    const loadData = useCallback(async (isRefresh = false) => {
        if (loading) return;
        const curPage = isRefresh ? 1 : page;
        setLoading(true);
        try {
            const data = await getMyCreateList(curPage, 20);
            if (data) {
                setList(prev => (isRefresh ? data : [...prev, ...data]));
                setHasMore(data.length === 20);
                setPage(curPage + 1);
            }
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
            setRefreshing(false);
        }
    }, [loading, page]);

    useEffect(() => {
        loadData(true);
    }, []);

    const onRefresh = () => {
        setRefreshing(true);
        loadData(true);
    };

    const onEndReached = () => {
        if (hasMore && !loading) {
            loadData();
        }
    };

    const getTypeName = (type: string) => {
        switch (type) {
            case 'COMMON': return '福利房';
            case 'PASSWORD': return '口令房';
            case 'EUROPEAN_GAS': return '欧气房';
            case 'ACHIEVEMENT': return '成就房';
            default: return '未知';
        }
    };

    const renderItem = ({ item }: { item: any }) => (
        <TouchableOpacity
            style={styles.itemContainer}
            onPress={() => router.push({ pathname: '/dimension/detail', params: { id: item.id } })}
        >
            <ImageBackground
                source={{ uri: Images.welfare.roomItemBg }}
                style={styles.itemBg}
                resizeMode="stretch"
            >
                <View style={styles.itemContent}>
                    <View style={styles.imgContainer}>
                        <ImageBackground source={{ uri: Images.welfare.roomItemImgBg }} style={styles.imgBg} resizeMode="contain">
                            {item.luckRoomGoodsList?.[0]?.spu?.cover && (
                                <Image
                                    source={{ uri: item.luckRoomGoodsList[0].spu.cover }}
                                    style={styles.goodsImg}
                                />
                            )}
                        </ImageBackground>
                    </View>

                    <View style={styles.infoContainer}>
                        <Text style={styles.roomName} numberOfLines={1}>{item.name}</Text>
                        <View style={styles.row}>
                            <Text style={styles.typeName}>{getTypeName(item.type)}</Text>
                            <Text style={styles.goodsNum}>共{item.goodsQuantity}件赠品</Text>
                        </View>
                    </View>

                    <View style={styles.btnContainer}>
                        <TouchableOpacity
                            style={styles.auditBtn}
                            onPress={() => {
                                if (item.status === 1 && item.participateMode === 1) {
                                    router.push({ pathname: '/dimension/audit_list', params: { id: item.id } } as any);
                                } else {
                                    router.push({ pathname: '/dimension/detail', params: { id: item.id } } as any);
                                }
                            }}
                        >
                            <Text style={styles.auditBtnText}>
                                {item.status === 1 && item.participateMode === 1 ? '审核列表' : '详情'}
                            </Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </ImageBackground>
        </TouchableOpacity>
    );

    return (
        <View style={styles.container}>
            <ImageBackground
                source={{ uri: Images.common.commonBg }}
                style={styles.background}
                resizeMode="cover"
            >
                <View style={[styles.header, { paddingTop: insets.top }]}>
                    <TouchableOpacity style={styles.backBtn} onPress={() => router.back()}>
                        <Ionicons name="chevron-back" size={24} color="#fff" />
                    </TouchableOpacity>
                    <Text style={styles.title}>我创建的</Text>
                    <View style={styles.placeholder} />
                </View>

                <FlatList
                    data={list}
                    renderItem={renderItem}
                    keyExtractor={(item) => item.id.toString()}
                    contentContainerStyle={styles.listContent}
                    onRefresh={onRefresh}
                    refreshing={refreshing}
                    onEndReached={onEndReached}
                    onEndReachedThreshold={0.5}
                    ListEmptyComponent={() => !loading && (
                        <View style={styles.emptyContainer as any}>
                            <Text style={styles.emptyText as any}>暂无创建记录</Text>
                        </View>
                    )}
                    ListFooterComponent={() => loading && (
                        <ActivityIndicator size="small" color="#fff" style={{ marginVertical: 20 }} />
                    )}
                />

                <View style={[styles.footer as any, { paddingBottom: Math.max(insets.bottom, 20) }]}>
                    <TouchableOpacity
                        style={styles.createBtn as any}
                        onPress={() => router.push('/dimension/create')}
                    >
                        <ImageBackground
                            source={{ uri: Images.common.loginBtn }}
                            style={styles.createBtnBg as any}
                            resizeMode="stretch"
                        >
                            <Text style={styles.createBtnText}>创建房间</Text>
                        </ImageBackground>
                    </TouchableOpacity>
                </View>

            </ImageBackground>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    background: {
        flex: 1,
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 15,
        height: 90,
    },
    backBtn: {
        width: 40,
        height: 40,
        justifyContent: 'center',
    },
    title: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#fff',
    },
    placeholder: {
        width: 40,
    },
    listContent: {
        padding: 15,
        paddingBottom: 120,
    },
    itemContainer: {
        height: 84,
        marginBottom: 6,
    },
    itemBg: {
        flex: 1,
    },
    itemContent: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 16,
        height: '100%',
    },
    imgContainer: {
        width: 58,
        height: 58,
        marginRight: 14,
    },
    imgBg: {
        width: '100%',
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
        padding: 7,
    },
    goodsImg: {
        width: '100%',
        height: '100%',
    },
    infoContainer: {
        flex: 1,
    },
    roomName: {
        fontSize: 14,
        color: '#fff',
        fontWeight: '400',
        marginBottom: 10,
        textShadowColor: 'rgba(0,0,0,1)',
        textShadowOffset: { width: 1, height: 1 },
        textShadowRadius: 1,
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    typeName: {
        fontSize: 12,
        color: '#2E0000',
        fontWeight: 'bold',
        marginRight: 10,
    },
    goodsNum: {
        fontSize: 10,
        color: '#2E0000',
        fontWeight: 'normal',
    },
    btnContainer: {
        marginLeft: 10,
    },
    auditBtn: {
        paddingHorizontal: 12,
        paddingVertical: 6,
    },
    auditBtnText: {
        fontSize: 12,
        color: '#fff',
        fontWeight: 'bold',
    },
    footer: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        alignItems: 'center',
        paddingTop: 10,
    },
    createBtn: {
        width: 160,
        height: 60,
    },
    createBtnBg: {
        width: '100%',
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
    },
    createBtnText: {
        fontSize: 15,
        fontWeight: '800',
        color: '#fff',
        textShadowColor: 'rgba(0,0,0,1)',
        textShadowOffset: { width: 1, height: 1 },
        textShadowRadius: 1,
    },
    emptyContainer: {
        paddingTop: 100,
        alignItems: 'center',
    },
    emptyText: {
        color: 'rgba(255,255,255,0.6)',
        fontSize: 14,
    },
});

export default CreateListScreen;
