import { Image } from 'expo-image';
import { useLocalSearchParams, useRouter } from 'expo-router';
import React, { useCallback, useEffect, useState } from 'react';
import {
    ActivityIndicator,
    Alert,
    Clipboard,
    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 { getOrders, OrderItem } from '@/services/mall';

const tabs = [
  { label: '全部', value: 'all' },
  { label: '待支付', value: 'to_pay' },
  { label: '待补款', value: 'to_payLeft' },
  { label: '待发货', value: 'to_delivery' },
  { label: '待收货', value: 'to_receive' },
  { label: '已完成', value: 'complete' },
  { label: '已取消', value: 'uncomplete' },
];

export default function ShopOrdersScreen() {
  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);
    return 0;
  });
  const [orders, setOrders] = useState<OrderItem[]>([]);
  const [page, setPage] = useState(1);

  const loadData = useCallback(async (tabValue?: string, refresh = false) => {
    if (refresh) {
      setRefreshing(true);
      setPage(1);
    } else {
      setLoading(true);
    }
    try {
      let tabId: any = tabValue;
      if (tabValue === 'all') tabId = undefined;
      
      const data = await getOrders(refresh ? 1 : page, 10, tabId);
      if (data?.records) {
        setOrders(refresh ? data.records : [...orders, ...data.records]);
      }
    } 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 goBox = () => {
    router.replace('/orders' as any);
  };

  const copyTradeNo = (tradeNo: string) => {
    Clipboard.setString(tradeNo);
    Alert.alert('提示', '订单号已复制');
  };

  const getStatusInfo = (status: number) => {
    switch (status) {
      case 0: return { text: '待支付', color: '#F62C71' };
      case 99: return { text: '已完成', color: '#20D7EF' };
      case 1: return { text: '待发货', color: '#F62C71' };
      case 2: return { text: '待收货', color: '#F62C71' };
      case 10: return { text: '已取消', color: '#999' };
      case 11: return { text: '超时取消', color: '#999' };
      case 12: return { text: '系统取消', color: '#999' };
      default: 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>

        <View style={styles.tabBar}>
          <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.tabScroll}>
            {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>
            ))}
          </ScrollView>
        </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 = getStatusInfo(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}>
                      <View style={styles.flexRow}>
                        <Text style={styles.orderTimeText}>下单时间：{item.createTime}</Text>
                        {item.type === 2 && <View style={styles.presellTag}><Text style={styles.presellText}>预售订单</Text></View>}
                      </View>
                      <Text style={[styles.orderStatusText, { 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 }}
                        style={styles.productImgBg}
                        resizeMode="stretch"
                      >
                        <Image source={{ uri: item.goodsCover }} style={styles.goodsImage} contentFit="cover" />
                      </ImageBackground>
                      <View style={styles.goodsInfo}>
                        <Text style={styles.goodsName} numberOfLines={1}>{item.goodsName}</Text>
                        <View style={styles.priceRow}>
                          <Text style={styles.goodsPrice}>¥{item.paymentAmount}</Text>
                          <Text style={styles.goodsQty}>X{item.quantity}</Text>
                        </View>
                        {(item.couponAmount ?? 0) > 0 && (
                          <Text style={styles.discountText}>使用优惠券-{item.couponAmount}</Text>
                        )}
                        
                        <View style={styles.totalRow}>
                          <View style={styles.totalItem}>
                            <Text style={styles.totalLabel}>总价：</Text>
                            <Text style={styles.totalValueSymbol}>¥</Text>
                            <Text style={styles.totalValue}>{item.totalAmount || item.paymentAmount}</Text>
                          </View>
                          <View style={[styles.totalItem, { marginLeft: 12 }]}>
                            <Text style={styles.payLabel}>{item.status === 0 ? '需付款：' : '实付款：'}</Text>
                            <Text style={styles.payValueSymbol}>¥</Text>
                            <Text style={styles.payValue}>{item.paidAmount || item.paymentAmount}</Text>
                          </View>
                        </View>
                      </View>
                    </View>

                    {/* 订单号 & 复制 */}
                    <View style={styles.orderNoRow}>
                      <Text style={styles.orderNo} numberOfLines={1}>订单号：{item.tradeNo}</Text>
                      <TouchableOpacity style={styles.copyBtn} onPress={() => copyTradeNo(item.tradeNo)}>
                        <Text style={styles.copyBtnText}>复制</Text>
                      </TouchableOpacity>
                    </View>

                    {/* 功能按钮 */}
                    <View style={styles.orderFooter}>
                      {item.status === 0 && (
                        <TouchableOpacity style={styles.actionBtn}>
                          <Text style={styles.actionBtnText}>付款</Text>
                        </TouchableOpacity>
                      )}
                      {item.status === 1 && (
                        <TouchableOpacity style={[styles.actionBtn, styles.infoBtn]}>
                          <Text style={styles.actionBtnText}>修改地址</Text>
                        </TouchableOpacity>
                      )}
                      {item.status === 2 && (
                        <TouchableOpacity style={styles.actionBtn}>
                          <Text style={styles.actionBtnText}>确认收货</Text>
                        </TouchableOpacity>
                      )}
                      {[2, 99].includes(item.status) && (
                        <TouchableOpacity style={[styles.actionBtn, { marginLeft: 8 }]}>
                          <Text style={styles.actionBtnText}>物流信息</Text>
                        </TouchableOpacity>
                      )}
                    </View>
                  </View>
                </ImageBackground>
              );
            })
          )}
          <View style={{ height: 80 }} />
        </ScrollView>

        {/* 奖池订单入口 */}
        <TouchableOpacity style={[styles.floatBtn, { bottom: insets.bottom + 154 }]} onPress={goBox}>
          <Image source={{ uri: Images.mine.boxOrder }} style={styles.floatIcon} 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: {
    height: 50,
    marginHorizontal: 10,
    marginBottom: 7,
  },
  tabScroll: {
    flex: 1,
  },
  tabItem: {
    width: 80,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 10,
    paddingTop: 4,
  },
  tabText: {
    color: '#000',
    fontSize: 14,
    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: 220,
  },
  cardContent: {
    paddingHorizontal: 20,
    paddingVertical: 10,
  },
  orderTop: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#CDCDCD',
    alignItems: 'center',
  },
  flexRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  orderTimeText: {
    fontSize: 12,
    color: '#333',
  },
  presellTag: {
    backgroundColor: '#F1423D',
    borderRadius: 11,
    paddingHorizontal: 8,
    height: 22,
    justifyContent: 'center',
    marginLeft: 8,
  },
  presellText: {
    color: '#fff',
    fontSize: 12,
  },
  orderStatusText: {
    fontSize: 12,
    fontWeight: '500',
  },
  timeoutText: {
    fontSize: 11,
    color: '#999',
    marginTop: 5,
  },
  orderMiddle: {
    flexDirection: 'row',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  productImgBg: {
    width: 70,
    height: 70,
    padding: 7,
  },
  goodsImage: {
    width: '100%',
    height: '100%',
    borderRadius: 3,
  },
  goodsInfo: {
    flex: 1,
    marginLeft: 12,
    justifyContent: 'center',
  },
  goodsName: {
    fontSize: 14,
    color: '#333',
    fontWeight: 'bold',
  },
  priceRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 8,
  },
  goodsPrice: {
    fontSize: 14,
    color: '#333',
    fontWeight: 'bold',
  },
  goodsQty: {
    fontSize: 12,
    color: '#333',
  },
  discountText: {
    fontSize: 12,
    color: '#F1423D',
    marginTop: 4,
  },
  totalRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8,
  },
  totalItem: {
    flexDirection: 'row',
    alignItems: 'baseline',
  },
  totalLabel: {
    fontSize: 11,
    color: '#666',
  },
  totalValueSymbol: {
    fontSize: 11,
    color: '#666',
  },
  totalValue: {
    fontSize: 14,
    color: '#666',
    fontWeight: 'bold',
  },
  payLabel: {
    fontSize: 12,
    color: '#F1423D',
  },
  payValueSymbol: {
    fontSize: 12,
    color: '#F1423D',
  },
  payValue: {
    fontSize: 18,
    color: '#F1423D',
    fontWeight: 'bold',
  },
  orderNoRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#CDCDCD',
  },
  orderNo: {
    flex: 1,
    fontSize: 12,
    color: '#666',
  },
  copyBtn: {
    paddingHorizontal: 6,
    paddingVertical: 3,
    backgroundColor: '#1FA4FF',
    borderRadius: 4,
  },
  copyBtnText: {
    color: '#fff',
    fontSize: 12,
  },
  orderFooter: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    paddingVertical: 12,
  },
  actionBtn: {
    height: 24,
    paddingHorizontal: 10,
    backgroundColor: '#1FA4FF',
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
  },
  infoBtn: {
    backgroundColor: '#1FA4FF',
  },
  actionBtnText: {
    color: '#fff',
    fontSize: 12,
  },
  floatBtn: {
    position: 'absolute',
    left: 10,
    width: 60,
    height: 63,
  },
  floatIcon: {
    width: '100%',
    height: '100%',
  },
});
