import { Images } from '@/constants/images';
import ServiceAward from '@/services/award';
import { Ionicons } from '@expo/vector-icons';
import { Stack, useRouter } from 'expo-router';
import React, { useState } from 'react';
import {
    ActivityIndicator,
    Dimensions,
    FlatList,
    Image,
    ImageBackground,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

const LEVEL_MAP: any = {
    D: { title: '普通', color: '#666666' },
    C: { title: '隐藏', color: '#9745e6' },
    B: { title: '欧皇', color: '#ff0000' },
    A: { title: '超神', color: '#ffae00' },
};

export default function StoreScreen() {
    const router = useRouter();
    const insets = useSafeAreaInsets();
    const [list, setList] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [tabIndex, setTabIndex] = useState(0);
    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);

    const tabs = ['未使用', '保险柜', '已提货'];

    React.useEffect(() => {
        setPage(1);
        setList([]);
        setHasMore(true);
        loadData(1);
    }, [tabIndex]);

    const loadData = async (pageNum: number) => {
        if (!hasMore && pageNum > 1) return;

        try {
            if (pageNum === 1) setLoading(true);

            let res;
            if (tabIndex === 0) {
                // Not in safe, unused (status=0)
                res = await ServiceAward.getStore(pageNum, 20, 0); // Use smaller size for pagination demo
            } else if (tabIndex === 1) {
                // In safe, unused (status=0)
                res = await ServiceAward.getStore(pageNum, 20, 1);
            } else {
                // Picked up
                res = await ServiceAward.getTakeList(pageNum, 20);
            }

            const records = Array.isArray(res) ? res : (res?.records || []);

            if (records.length < 20) {
                setHasMore(false);
            }

            if (pageNum === 1) {
                setList(records);
            } else {
                setList(prev => [...prev, ...records]);
            }
        } catch (e) {
            console.error(e);
        } finally {
            setLoading(false);
        }
    };

    const handleLoadMore = () => {
        if (!loading && hasMore) {
            const nextPage = page + 1;
            setPage(nextPage);
            loadData(nextPage);
        }
    };

    const handleLock = async (item: any) => {
        // Implement lock/unlock logic if needed
    };

    const renderItem = ({ item }: { item: any }) => (
        <ImageBackground
            source={{ uri: Images.mine.storeItemBg }}
            style={styles.cell}
            resizeMode="stretch"
        >
            <View style={styles.cellHeader}>
                <View style={styles.headerLeft}>
                    <View style={[styles.checkBox]} />
                    <Text style={[styles.levelTitle, { color: LEVEL_MAP[item.level]?.color || '#333' }]}>
                        {LEVEL_MAP[item.level]?.title || '未知'}
                    </Text>
                </View>
                <TouchableOpacity style={styles.lockBox} onPress={() => handleLock(item)}>
                    <Text style={styles.lockText}>{item.safeFlag !== 1 ? '锁定' : '解锁'}</Text>
                    <Image
                        source={{ uri: item.safeFlag !== 1 ? Images.mine.lock : Images.mine.unlock }}
                        style={styles.lockIcon}
                    />
                </TouchableOpacity>
            </View>

            <View style={styles.cellBody}>
                <ImageBackground
                    source={{ uri: Images.mine.storeGoodsImgBg }}
                    style={styles.goodsImgBg}
                >
                    <Image source={{ uri: item.spu?.cover }} style={styles.goodsImg} resizeMode="contain" />
                </ImageBackground>
                <View style={styles.goodsInfo}>
                    <Text style={styles.goodsName} numberOfLines={2}>{item.spu?.name}</Text>
                    <Text style={styles.goodsSource}>
                        从{item.fromRelationType === 'LUCK' ? '奖池' : '其他'}获得
                    </Text>
                </View>
            </View>
        </ImageBackground>
    );

    return (
        <View style={styles.container}>
            <Stack.Screen options={{ headerShown: false }} />
            <StatusBar barStyle="light-content" />
            <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>

            <ImageBackground
                source={{ uri: Images.mine.kaixinMineBg }}
                style={styles.background}
                resizeMode="cover"
            >
                <Image
                    source={{ uri: Images.mine.kaixinMineHeadBg }}
                    style={styles.headerBg}
                    resizeMode="cover"
                />

                <View style={[styles.content, { paddingTop: insets.top + 50 }]}>
                    {/* Tabs */}
                    <View style={styles.tabs}>
                        {tabs.map((tab, index) => (
                            <TouchableOpacity
                                key={index}
                                style={[styles.tabItem, tabIndex === index && styles.tabItemActive]}
                                onPress={() => setTabIndex(index)}
                            >
                                <Text style={[styles.tabText, tabIndex === index && styles.tabTextActive]}>{tab}</Text>
                                {tabIndex === index && <View style={styles.tabLine} />}
                            </TouchableOpacity>
                        ))}
                    </View>

                    <FlatList
                        data={list}
                        renderItem={renderItem}
                        keyExtractor={(item, index) => index.toString()}
                        contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 100 }}
                        onEndReached={handleLoadMore}
                        onEndReachedThreshold={0.1}
                        ListFooterComponent={
                            loading && list.length > 0 ? (
                                <ActivityIndicator color="#fff" style={{ marginVertical: 10 }} />
                            ) : null
                        }
                        ListEmptyComponent={
                            !loading ? (
                                <View style={styles.emptyBox}>
                                    <Text style={styles.emptyText}>暂无物品</Text>
                                </View>
                            ) : null
                        }
                    />
                </View>
            </ImageBackground>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#1a1a2e',
    },
    header: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        zIndex: 100,
        alignItems: 'center',
        paddingBottom: 10,
    },
    headerBg: {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: 260,
    },
    backBtn: {
        position: 'absolute',
        left: 10,
        bottom: 10,
        zIndex: 101,
    },
    title: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    background: {
        flex: 1,
        width: '100%',
        height: '100%',
    },
    content: {
        flex: 1,
    },
    tabs: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        marginBottom: 10,
    },
    tabItem: {
        paddingVertical: 10,
        paddingHorizontal: 10,
        alignItems: 'center',
    },
    tabItemActive: {},
    tabText: {
        color: '#aaa',
        fontSize: 14,
    },
    tabTextActive: {
        color: '#fff',
        fontWeight: 'bold',
        fontSize: 16,
    },
    tabLine: {
        width: 20,
        height: 3,
        backgroundColor: '#fff',
        marginTop: 5,
        borderRadius: 2,
    },
    cell: {
        width: '100%',
        height: 154,
        marginBottom: 10,
        padding: 15,
    },
    cellHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        borderBottomWidth: 1,
        borderBottomColor: 'rgba(0,0,0,0.1)',
        paddingBottom: 10,
        marginBottom: 10,
    },
    headerLeft: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    checkBox: {
        width: 16,
        height: 16,
        borderWidth: 1,
        borderColor: '#999',
        marginRight: 10,
        backgroundColor: '#fff',
    },
    levelTitle: {
        fontSize: 16,
        fontWeight: 'bold',
    },
    lockBox: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    lockText: {
        fontSize: 12,
        color: '#666',
    },
    lockIcon: {
        width: 16,
        height: 16,
        marginLeft: 5,
    },
    cellBody: {
        flexDirection: 'row',
    },
    goodsImgBg: {
        width: 65,
        height: 65,
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: 10,
    },
    goodsImg: {
        width: 60,
        height: 60,
    },
    goodsInfo: {
        flex: 1,
        justifyContent: 'space-between',
    },
    goodsName: {
        fontSize: 14,
        color: '#333',
        fontWeight: 'bold',
    },
    goodsSource: {
        fontSize: 12,
        color: '#999',
    },
    emptyBox: {
        marginTop: 100,
        alignItems: 'center',
    },
    emptyText: {
        color: '#999',
    },
});
