import { Image } from 'expo-image';
import { useRouter } from 'expo-router';
import React, { useCallback, useEffect, useState } from 'react';
import {
    Alert,
    ImageBackground,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { Images } from '@/constants/images';
import { getMyBoxes, openBox } from '@/services/award';

interface BoxItem {
  id: string;
  boxName: string;
  boxCover: string;
}

export default function BoxListScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const [list, setList] = useState<BoxItem[]>([]);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  const loadData = useCallback(async () => {
    try {
      setLoading(true);
      const res = await getMyBoxes();
      // 确保返回的是数组
      setList(Array.isArray(res) ? res : []);
    } catch (error) {
      console.error('获取宝箱列表失败:', error);
      setList([]);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const toggleSelect = (item: BoxItem) => {
    if (!item.id) return;
    
    setSelectedIds(prev => {
      const index = prev.indexOf(item.id);
      if (index > -1) {
        return prev.filter(id => id !== item.id);
      } else {
        return [...prev, item.id];
      }
    });
  };

  const isSelected = (id: string) => selectedIds.includes(id);

  const isAllSelected = list.length > 0 && selectedIds.length === list.length;

  const selectAll = () => {
    if (isAllSelected) {
      setSelectedIds([]);
    } else {
      setSelectedIds(list.map(item => item.id));
    }
  };

  const openSelectedBoxes = async () => {
    if (selectedIds.length === 0) {
      Alert.alert('提示', '请先选择宝箱');
      return;
    }

    try {
      const boxIds = selectedIds.join(',');
      const res = await openBox({ boxIds });
      
      if (res.code === 0) {
        // TODO: 显示开箱结果弹窗
        Alert.alert('开箱成功', '恭喜获得奖品！', [
          { text: '确定', onPress: () => {
            setSelectedIds([]);
            loadData();
          }}
        ]);
      } else {
        Alert.alert('提示', res.msg || '开箱失败');
      }
    } catch (error) {
      console.error('开箱失败:', error);
      Alert.alert('提示', '开箱失败，请重试');
    }
  };

  const handleBack = () => {
    router.back();
  };

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" />
      <ImageBackground
        source={{ uri: Images.mine.kaixinMineBg }}
        style={styles.background}
        resizeMode="cover"
      >
        {/* 顶部导航 */}
        <View style={[styles.header, { paddingTop: insets.top }]}>
          <TouchableOpacity style={styles.backBtn} onPress={handleBack}>
            <Text style={styles.backIcon}>‹</Text>
          </TouchableOpacity>
          <Text style={styles.title}>宝箱</Text>
          <View style={styles.placeholder} />
        </View>

        {/* 内容区域 */}
        <View style={styles.wrapper}>
          <View style={styles.contentBox}>
            <ScrollView 
              showsVerticalScrollIndicator={false}
              contentContainerStyle={styles.scrollContent}
            >
              <View style={styles.itemList}>
                {list.map((item, index) => (
                  <TouchableOpacity
                    key={item.id || index}
                    style={styles.item}
                    onPress={() => toggleSelect(item)}
                    activeOpacity={0.8}
                  >
                    <View style={[
                      styles.itemCenter,
                      isSelected(item.id) && styles.itemSelected
                    ]}>
                      <View style={styles.imgBox}>
                        <Image
                          source={{ uri: item.boxCover }}
                          style={styles.boxImage}
                          contentFit="cover"
                        />
                        {isSelected(item.id) && (
                          <View style={styles.selectMask}>
                            <Text style={styles.checkIcon}>✓</Text>
                          </View>
                        )}
                      </View>
                      <View style={styles.textBox}>
                        <Text style={styles.boxName} numberOfLines={1}>
                          {item.boxName}
                        </Text>
                      </View>
                    </View>
                  </TouchableOpacity>
                ))}
              </View>

              {list.length === 0 && !loading && (
                <View style={styles.empty}>
                  <Text style={styles.emptyText}>暂无宝箱</Text>
                </View>
              )}
            </ScrollView>
          </View>
        </View>

        {/* 底部按钮 */}
        <View style={[styles.bottomBtnBox, { paddingBottom: insets.bottom + 80 }]}>
          <View style={styles.btnGroup}>
            <TouchableOpacity
              style={styles.selectAllBtn}
              onPress={selectAll}
            >
              <ImageBackground
                source={{ uri: Images.common.loginBtn }}
                style={styles.btnBg}
                resizeMode="stretch"
              >
                <Text style={styles.btnText}>
                  {isAllSelected ? '取消全选' : '全选'}
                </Text>
              </ImageBackground>
            </TouchableOpacity>
            
            <TouchableOpacity
              style={[
                styles.openBtn,
                selectedIds.length === 0 && styles.openBtnDisabled
              ]}
              onPress={openSelectedBoxes}
              disabled={selectedIds.length === 0}
            >
              <ImageBackground
                source={{ uri: Images.common.loginBtn }}
                style={styles.btnBg}
                resizeMode="stretch"
              >
                <Text style={styles.btnText}>
                  开启宝箱 {selectedIds.length > 0 ? `(${selectedIds.length})` : ''}
                </Text>
              </ImageBackground>
            </TouchableOpacity>
          </View>
        </View>
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a2e',
  },
  background: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 10,
    height: 80,
    zIndex: 100,
  },
  backBtn: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  backIcon: {
    fontSize: 32,
    color: '#fff',
    fontWeight: 'bold',
  },
  title: {
    fontSize: 15,
    fontWeight: 'bold',
    color: '#fff',
    textAlign: 'center',
  },
  placeholder: {
    width: 40,
  },
  wrapper: {
    flex: 1,
    padding: 10,
  },
  contentBox: {
    flex: 1,
    backgroundColor: '#fff',
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#000',
    padding: 10,
  },
  scrollContent: {
    paddingBottom: 60,
  },
  itemList: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  item: {
    width: '33.33%',
    height: 110,
    padding: 5,
  },
  itemCenter: {
    width: '100%',
    height: '100%',
    alignItems: 'center',
  },
  itemSelected: {
    transform: [{ scale: 0.95 }],
    opacity: 0.8,
  },
  imgBox: {
    width: '85%',
    height: '75%',
    position: 'relative',
  },
  boxImage: {
    width: '100%',
    height: '100%',
    borderRadius: 8,
  },
  selectMask: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.4)',
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  checkIcon: {
    fontSize: 30,
    color: '#fff',
    fontWeight: 'bold',
  },
  textBox: {
    width: '100%',
    alignItems: 'center',
    marginTop: 4,
  },
  boxName: {
    fontSize: 13,
    color: '#000',
  },
  empty: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 100,
  },
  emptyText: {
    fontSize: 14,
    color: '#999',
  },
  bottomBtnBox: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    padding: 10,
  },
  btnGroup: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    width: '90%',
    alignSelf: 'center',
  },
  selectAllBtn: {
    width: '30%',
    height: 44,
    marginRight: 10,
  },
  openBtn: {
    flex: 1,
    height: 44,
  },
  openBtnDisabled: {
    opacity: 0.6,
  },
  btnBg: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  btnText: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#000',
  },
});
