import { Image } from 'expo-image';
import { 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 { 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 OrdersScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();

  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [activeTab, setActiveTab] = useState(0);
  const [orders, setOrders] = useState<OrderItem[]>([]);
  const [page, setPage] = useState(1);

  const loadData = useCallback(async (tab?: number, refresh = false) => {
    if (refresh) {
      setRefreshing(true);
      setPage(1);
    } else {
      setLoading(true);
    }
    try {
      const data = await getOrders(refresh ? 1 : page, 10, tab);
      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 goToDetail = (tradeNo: string) => {
    router.push(`/orders/${tradeNo}` as any);
  };

  const goBack = () => {
    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={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}
              style={[styles.tabItem, activeTab === index && styles.tabItemActive]}
              onPress={() => switchTab(index)}
            >
              <Text style={[styles.tabText, activeTab === index && styles.tabTextActive]}>
                {tab.label}
              </Text>
            </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) => (
              <TouchableOpacity
                key={item.tradeNo}
                style={styles.orderItem}
                onPress={() => goToDetail(item.tradeNo)}
              >
                <ImageBackground
                  source={{ uri: Images.common.itemBg }}
                  style={styles.orderItemBg}
                  resizeMode="stretch"
                >
                  <View style={styles.orderHeader}>
                    <Text style={styles.orderNo}>订单号：{item.tradeNo}</Text>
                    <Text style={styles.orderStatus}>{item.statusText}</Text>
                  </View>
                  <View style={styles.orderContent}>
                    <Image source={item.goodsCover} style={styles.goodsImage} contentFit="cover" />
                    <View style={styles.goodsInfo}>
                      <Text style={styles.goodsName} numberOfLines={2}>{item.goodsName}</Text>
                      <View style={styles.goodsBottom}>
                        <Text style={styles.goodsPrice}>¥{item.paymentAmount}</Text>
                        <Text style={styles.goodsQty}>x{item.quantity}</Text>
                      </View>
                    </View>
                  </View>
                  <View style={styles.orderFooter}>
                    <Text style={styles.orderTime}>{item.createTime}</Text>
                    <View style={styles.orderActions}>
                      {item.status === 1 && (
                        <TouchableOpacity style={styles.actionBtn}>
                          <Text style={styles.actionBtnText}>去支付</Text>
                        </TouchableOpacity>
                      )}
                      {item.status === 3 && (
                        <TouchableOpacity style={styles.actionBtn}>
                          <Text style={styles.actionBtnText}>确认收货</Text>
                        </TouchableOpacity>
                      )}
                    </View>
                  </View>
                </ImageBackground>
              </TouchableOpacity>
            ))
          )}
          <View style={{ height: 20 }} />
        </ScrollView>
      </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: 24,
  },
  headerTitle: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  placeholder: {
    width: 40,
  },
  tabBar: {
    flexDirection: 'row',
    backgroundColor: 'rgba(255,255,255,0.1)',
    marginHorizontal: 15,
    borderRadius: 8,
    paddingVertical: 5,
  },
  tabItem: {
    flex: 1,
    alignItems: 'center',
    paddingVertical: 8,
  },
  tabItemActive: {
    borderBottomWidth: 2,
    borderBottomColor: '#ff6b00',
  },
  tabText: {
    color: '#999',
    fontSize: 14,
  },
  tabTextActive: {
    color: '#ff6b00',
    fontWeight: '600',
  },
  scrollView: {
    flex: 1,
    paddingHorizontal: 15,
  },
  loadingContainer: {
    paddingTop: 100,
    alignItems: 'center',
  },
  emptyContainer: {
    paddingTop: 100,
    alignItems: 'center',
  },
  emptyText: {
    color: '#999',
    fontSize: 14,
  },
  orderItem: {
    marginTop: 10,
  },
  orderItemBg: {
    borderRadius: 12,
    overflow: 'hidden',
  },
  orderHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 12,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(0,0,0,0.1)',
  },
  orderNo: {
    color: '#666',
    fontSize: 12,
  },
  orderStatus: {
    color: '#ff6b00',
    fontSize: 13,
    fontWeight: '500',
  },
  orderContent: {
    flexDirection: 'row',
    padding: 12,
  },
  goodsImage: {
    width: 80,
    height: 80,
    borderRadius: 8,
    backgroundColor: '#fff',
  },
  goodsInfo: {
    flex: 1,
    marginLeft: 12,
    justifyContent: 'space-between',
  },
  goodsName: {
    color: '#333',
    fontSize: 14,
    lineHeight: 20,
  },
  goodsBottom: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  goodsPrice: {
    color: '#ff6b00',
    fontSize: 16,
    fontWeight: '600',
  },
  goodsQty: {
    color: '#666',
    fontSize: 13,
  },
  orderFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 12,
    borderTopWidth: 1,
    borderTopColor: 'rgba(0,0,0,0.1)',
  },
  orderTime: {
    color: '#999',
    fontSize: 12,
  },
  orderActions: {
    flexDirection: 'row',
  },
  actionBtn: {
    paddingHorizontal: 16,
    paddingVertical: 6,
    backgroundColor: '#ff6b00',
    borderRadius: 15,
    marginLeft: 10,
  },
  actionBtnText: {
    color: '#fff',
    fontSize: 13,
  },
});
