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

import { Images } from '@/constants/images';
import { getAwardOrders } from '@/services/award';

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

const tabs = [
  { label: '已完成', value: 'complete' },
  { label: '未完成', value: 'uncomplete' },
];

interface AwardOrderItem {
  tradeNo: string;
  createTime: string;
  status: number;
  luckPool: {
    name: string;
    cover: string;
  };
  price: number;
  quantity: number;
  couponAmount: number;
  magicAmount: number;
  paymentAmount: number;
  paymentTimeoutTime?: string;
  itemList?: Array<{
    spu: { cover: string };
    level: string;
  }>;
}

export default function OrdersScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const params = useLocalSearchParams();

  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [activeTab, setActiveTab] = useState(() => {
    if (params.active) return parseInt(params.active as string, 10);
    if (params.tab === '4') return 1;
    return 0;
  });
  const [orders, setOrders] = useState<AwardOrderItem[]>([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);

  const loadData = useCallback(async (tabValue?: string, refresh = false) => {
    if (refresh) {
      setRefreshing(true);
      setPage(1);
    } else {
      setLoading(true);
    }
    try {
      const data = await getAwardOrders(refresh ? 1 : page, 10, tabValue);
      console.log('奖池订单数据:', tabValue, data);
      
      let records: AwardOrderItem[] = [];
      if (Array.isArray(data)) {
        records = data;
      } else if (data?.records) {
        records = data.records;
      }

      if (records.length > 0) {
        setOrders(refresh ? records : [...orders, ...records]);
        setPage((prev) => (refresh ? 2 : prev + 1));
        setHasMore(records.length === 10);
      } else {
        if (refresh) setOrders([]);
        setHasMore(false);
      }
    } catch (error) {
      console.error('加载订单失败:', error);
    }
    setLoading(false);
    setRefreshing(false);
  }, [page, orders]);

  useEffect(() => {
    loadData(tabs[activeTab].value, true);
  }, [activeTab]);

  const onRefresh = () => {
    loadData(tabs[activeTab].value, true);
  };

  const switchTab = (index: number) => {
    if (index !== activeTab) {
      setActiveTab(index);
      setOrders([]);
    }
  };

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

  const goToShopOrders = () => {
    router.push('/orders/shop' as any);
  };

  const getStatusText = (status: number) => {
    if (status === 99) return { text: '已完成', color: '#20D7EF' };
    if (status === 0) return { text: '待支付', color: '#F62C71' };
    if (status === 10) return { text: '用户取消', color: '#999' };
    if (status === 11) return { text: '超时取消', color: '#999' };
    return { text: '未知', color: '#999' };
  };

  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={goBack}>
            <Text style={styles.backText}>‹</Text>
          </TouchableOpacity>
          <Text style={styles.headerTitle}>奖池订单</Text>
          <View style={styles.placeholder} />
        </View>

        {/* Tab 栏 */}
        <View style={styles.tabBar}>
          {tabs.map((tab, index) => (
            <TouchableOpacity
              key={index}
              onPress={() => switchTab(index)}
              activeOpacity={0.8}
            >
              <ImageBackground
                source={{ uri: activeTab === index ? Images.home.typeBgOn : Images.home.typeBg }}
                style={styles.tabItem}
                resizeMode="stretch"
              >
                <Text style={[styles.tabText, activeTab === index && styles.tabTextActive]}>
                  {tab.label}
                </Text>
              </ImageBackground>
            </TouchableOpacity>
          ))}
        </View>

        <ScrollView
          style={styles.scrollView}
          showsVerticalScrollIndicator={false}
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor="#fff" />
          }
        >
          {loading && orders.length === 0 ? (
            <View style={styles.loadingContainer}>
              <ActivityIndicator size="large" color="#fff" />
            </View>
          ) : orders.length === 0 ? (
            <View style={styles.emptyContainer}>
              <Text style={styles.emptyText}>暂无订单</Text>
            </View>
          ) : (
            orders.map((item) => {
              const statusInfo = getStatusText(item.status);
              return (
                <ImageBackground
                  key={item.tradeNo}
                  source={{ uri: Images.common.itemBg }}
                  style={styles.orderCard}
                  resizeMode="stretch"
                >
                  <View style={styles.cardContent}>
                    {/* 顶部信息 */}
                    <View style={styles.orderTop}>
                      <Text style={styles.orderTime}>下单时间：{item.createTime}</Text>
                      <Text style={[styles.orderStatus, { color: statusInfo.color }]}>
                        {statusInfo.text}
                      </Text>
                    </View>
                    {item.status === 0 && item.paymentTimeoutTime && (
                      <Text style={styles.timeoutText}>
                        {item.paymentTimeoutTime} 将自动取消该订单，如有优惠券，将自动退回
                      </Text>
                    )}

                    {/* 中间商品信息 */}
                    <View style={styles.orderMiddle}>
                      <ImageBackground 
                        source={{ uri: Images.box?.detail?.firstItemBg || Images.common.itemBg }} 
                        style={styles.productImgBg}
                      >
                        <Image 
                          source={{ uri: item.luckPool?.cover }} 
                          style={styles.productImg} 
                          contentFit="cover" 
                        />
                      </ImageBackground>
                      <View style={styles.productInfo}>
                        <Text style={styles.productName} numberOfLines={1}>{item.luckPool?.name}</Text>
                        <View style={styles.priceRow}>
                          <Text style={styles.priceText}>¥{item.price}</Text>
                          <Text style={styles.qtyText}>X{item.quantity}</Text>
                        </View>
                        <Text style={styles.discountText}>
                          使用优惠券-{item.couponAmount} 使用果实-{item.magicAmount}
                        </Text>
                        <View style={styles.paymentRow}>
                          <Text style={styles.discountText}>实付款：</Text>
                          <Text style={styles.paymentAmount}>¥{item.paymentAmount}</Text>
                        </View>
                      </View>
                    </View>

                    {/* 底部商品列表 */}
                    {item.status === 99 && item.itemList && item.itemList.length > 0 && (
                      <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.itemList}>
                        {item.itemList.map((goods, idx) => {
                          const levelInfo = LEVEL_MAP[goods.level] || LEVEL_MAP.D;
                          return (
                            <View key={idx} style={styles.itemBox}>
                              <View style={styles.itemImgBox}>
                                <Image source={{ uri: goods.spu?.cover }} style={styles.itemImg} contentFit="contain" />
                              </View>
                              <View style={[styles.levelTag, { backgroundColor: levelInfo.color }]}>
                                <Text style={styles.levelText}>{levelInfo.title}</Text>
                              </View>
                            </View>
                          );
                        })}
                      </ScrollView>
                    )}

                    {/* 未完成订单显示订单号 */}
                    {item.status !== 99 && (
                      <View style={styles.orderNoRow}>
                        <Text style={styles.orderNoText} numberOfLines={1}>订单号：{item.tradeNo}</Text>
                        <TouchableOpacity style={styles.copyBtn}>
                          <Text style={styles.copyBtnText}>复制</Text>
                        </TouchableOpacity>
                      </View>
                    )}
                  </View>
                </ImageBackground>
              );
            })
          )}
          <View style={{ height: 80 }} />
        </ScrollView>

        {/* 商城订单入口 */}
        <TouchableOpacity style={[styles.shopOrderBtn, { bottom: insets.bottom + 154 }]} onPress={goToShopOrders}>
          <Image source={{ uri: Images.mine.shopOrder }} style={styles.shopOrderIcon} contentFit="contain" />
        </TouchableOpacity>
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a2e',
  },
  background: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 15,
    paddingBottom: 10,
  },
  backBtn: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  backText: {
    color: '#fff',
    fontSize: 32,
    fontWeight: 'bold',
  },
  headerTitle: {
    color: '#fff',
    fontSize: 15,
    fontWeight: 'bold',
  },
  placeholder: {
    width: 40,
  },
  tabBar: {
    flexDirection: 'row',
    marginHorizontal: 10,
    marginBottom: 15,
  },
  tabItem: {
    width: 80, // 原项目 160rpx
    height: 40, // 原项目 80rpx
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 10, // 原项目 20rpx
  },
  tabText: {
    color: '#000',
    fontSize: 14, // 原项目 28rpx
    fontWeight: '400',
  },
  tabTextActive: {
    fontWeight: 'bold',
  },
  scrollView: {
    flex: 1,
    paddingHorizontal: 10,
  },
  loadingContainer: {
    paddingTop: 100,
    alignItems: 'center',
  },
  emptyContainer: {
    paddingTop: 100,
    alignItems: 'center',
  },
  emptyText: {
    color: '#999',
    fontSize: 14,
  },
  orderCard: {
    marginVertical: 10,
    minHeight: 200,
  },
  cardContent: {
    padding: 15,
  },
  orderTop: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingBottom: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#CDCDCD',
  },
  orderTime: {
    fontSize: 12,
    color: '#666',
  },
  orderStatus: {
    fontSize: 12,
  },
  timeoutText: {
    fontSize: 11,
    color: '#999',
    marginTop: 5,
  },
  orderMiddle: {
    flexDirection: 'row',
    paddingVertical: 12,
  },
  productImgBg: {
    width: 90,
    height: 90,
    padding: 8,
  },
  productImg: {
    width: '100%',
    height: '100%',
    borderRadius: 3,
  },
  productInfo: {
    flex: 1,
    marginLeft: 12,
    justifyContent: 'space-between',
  },
  productName: {
    fontSize: 14,
    color: '#333',
    fontWeight: 'bold',
  },
  priceRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  priceText: {
    fontSize: 14,
    color: '#333',
  },
  qtyText: {
    fontSize: 14,
    color: '#333',
  },
  discountText: {
    fontSize: 12,
    color: '#F1423D',
    fontWeight: '500',
  },
  paymentRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  paymentAmount: {
    fontSize: 16,
    color: '#F1423D',
    fontWeight: 'bold',
  },
  itemList: {
    marginTop: 5,
    paddingBottom: 10,
  },
  itemBox: {
    marginRight: 10,
    alignItems: 'center',
  },
  itemImgBox: {
    width: 60,
    height: 65,
    backgroundColor: '#fff',
    borderRadius: 3,
    overflow: 'hidden',
  },
  itemImg: {
    width: '100%',
    height: '100%',
  },
  levelTag: {
    width: '100%',
    paddingVertical: 2,
    alignItems: 'center',
  },
  levelText: {
    color: '#fff',
    fontSize: 10,
    fontWeight: 'bold',
  },
  orderNoRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    height: 29,
  },
  orderNoText: {
    flex: 1,
    fontSize: 12,
    color: '#666',
  },
  copyBtn: {
    paddingHorizontal: 6,
    paddingVertical: 3,
    backgroundColor: '#1FA4FF',
    borderRadius: 4,
  },
  copyBtnText: {
    color: '#fff',
    fontSize: 12,
  },
  shopOrderBtn: {
    position: 'absolute',
    left: 10,
    width: 60,
    height: 63,
  },
  shopOrderIcon: {
    width: '100%',
    height: '100%',
  },
});
