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

import { Images } from '@/constants/images';
import { getAwardExpress, getAwardPackages } from '@/services/award';

interface PackageItem {
  id: string;
  expressNo: string;
  expressCompany: string;
  itemList: Array<{ cover: string; name: string }>;
}

interface ExpressDetail {
  expressNo: string;
  expressCompany: string;
  traces: Array<{ time: string; content: string }>;
}

export default function PackagesScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const { tradeNo } = useLocalSearchParams<{ tradeNo: string }>();

  const [loading, setLoading] = useState(true);
  const [packages, setPackages] = useState<PackageItem[]>([]);
  const [selectedPackage, setSelectedPackage] = useState<PackageItem | null>(null);
  const [expressDetail, setExpressDetail] = useState<ExpressDetail | null>(null);
  const [loadingExpress, setLoadingExpress] = useState(false);

  const loadPackages = useCallback(async () => {
    if (!tradeNo) return;
    setLoading(true);
    try {
      const res = await getAwardPackages(tradeNo);
      if (res && Array.isArray(res)) {
        setPackages(res);
        if (res.length > 0) {
          setSelectedPackage(res[0]);
          loadExpressDetail(res[0].id);
        }
      }
    } catch (e) {
      console.error('加载包裹信息失败:', e);
    }
    setLoading(false);
  }, [tradeNo]);

  const loadExpressDetail = async (packageId: string) => {
    if (!tradeNo) return;
    setLoadingExpress(true);
    try {
      const res = await getAwardExpress(tradeNo, packageId);
      setExpressDetail(res);
    } catch (e) {
      console.error('加载物流详情失败:', e);
    }
    setLoadingExpress(false);
  };

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

  const selectPackage = (pkg: PackageItem) => {
    setSelectedPackage(pkg);
    loadExpressDetail(pkg.id);
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#fff" />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" />
      <ImageBackground source={{ uri: Images.mine.kaixinMineBg }} style={styles.background} resizeMode="cover">
        <Image source={{ uri: Images.mine.kaixinMineHeadBg }} style={styles.headerBg} contentFit="cover" />
        
        {/* 顶部导航 */}
        <View style={[styles.header, { paddingTop: insets.top }]}>
          <TouchableOpacity style={styles.backBtn} onPress={() => router.back()}>
            <Text style={styles.backIcon}>‹</Text>
          </TouchableOpacity>
          <Text style={styles.title}>物流信息</Text>
          <View style={styles.placeholder} />
        </View>

        <ScrollView style={[styles.content, { paddingTop: insets.top + 50 }]} showsVerticalScrollIndicator={false}>
          {packages.length === 0 ? (
            <View style={styles.emptyBox}>
              <Text style={styles.emptyText}>暂无物流信息</Text>
            </View>
          ) : (
            <>
              {/* 包裹选择 */}
              {packages.length > 1 && (
                <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.packageTabs}>
                  {packages.map((pkg, idx) => (
                    <TouchableOpacity
                      key={pkg.id}
                      style={[styles.packageTab, selectedPackage?.id === pkg.id && styles.packageTabActive]}
                      onPress={() => selectPackage(pkg)}
                    >
                      <Text style={[styles.packageTabText, selectedPackage?.id === pkg.id && styles.packageTabTextActive]}>
                        包裹{idx + 1}
                      </Text>
                    </TouchableOpacity>
                  ))}
                </ScrollView>
              )}

              {/* 快递信息 */}
              {selectedPackage && (
                <View style={styles.expressInfo}>
                  <Text style={styles.expressCompany}>{selectedPackage.expressCompany || '快递公司'}</Text>
                  <Text style={styles.expressNo}>快递单号：{selectedPackage.expressNo || '暂无'}</Text>
                </View>
              )}

              {/* 商品列表 */}
              {selectedPackage && selectedPackage.itemList && (
                <View style={styles.goodsSection}>
                  <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                    {selectedPackage.itemList.map((item, idx) => (
                      <View key={idx} style={styles.goodsItem}>
                        <Image source={{ uri: item.cover }} style={styles.goodsImg} contentFit="contain" />
                      </View>
                    ))}
                  </ScrollView>
                </View>
              )}

              {/* 物流轨迹 */}
              {loadingExpress ? (
                <ActivityIndicator color="#fff" style={{ marginTop: 20 }} />
              ) : expressDetail && expressDetail.traces && expressDetail.traces.length > 0 ? (
                <View style={styles.tracesSection}>
                  <Text style={styles.tracesTitle}>物流轨迹</Text>
                  {expressDetail.traces.map((trace, idx) => (
                    <View key={idx} style={styles.traceItem}>
                      <View style={styles.traceDot} />
                      {idx < expressDetail.traces.length - 1 && <View style={styles.traceLine} />}
                      <View style={styles.traceContent}>
                        <Text style={styles.traceTime}>{trace.time}</Text>
                        <Text style={styles.traceText}>{trace.content}</Text>
                      </View>
                    </View>
                  ))}
                </View>
              ) : (
                <View style={styles.noTraces}>
                  <Text style={styles.noTracesText}>暂无物流轨迹</Text>
                </View>
              )}
            </>
          )}
          <View style={{ height: 50 }} />
        </ScrollView>
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#1a1a2e' },
  background: { flex: 1 },
  loadingContainer: { flex: 1, backgroundColor: '#1a1a2e', justifyContent: 'center', alignItems: 'center' },
  headerBg: { position: 'absolute', top: 0, left: 0, width: '100%', height: 160 },
  header: { position: 'absolute', top: 0, left: 0, right: 0, zIndex: 100, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 10, paddingBottom: 10 },
  backBtn: { width: 40, height: 40, justifyContent: 'center', alignItems: 'center' },
  backIcon: { fontSize: 32, color: '#fff', fontWeight: 'bold' },
  title: { color: '#fff', fontSize: 16, fontWeight: 'bold' },
  placeholder: { width: 40 },
  content: { flex: 1, paddingHorizontal: 15 },
  emptyBox: { marginTop: 100, alignItems: 'center' },
  emptyText: { color: '#999', fontSize: 14 },
  packageTabs: { flexDirection: 'row', marginBottom: 15 },
  packageTab: { paddingHorizontal: 20, paddingVertical: 10, backgroundColor: 'rgba(255,255,255,0.1)', borderRadius: 20, marginRight: 10 },
  packageTabActive: { backgroundColor: '#FC7D2E' },
  packageTabText: { color: '#aaa', fontSize: 14 },
  packageTabTextActive: { color: '#fff' },
  expressInfo: { backgroundColor: 'rgba(255,255,255,0.1)', borderRadius: 10, padding: 15, marginBottom: 15 },
  expressCompany: { color: '#fff', fontSize: 16, fontWeight: 'bold', marginBottom: 5 },
  expressNo: { color: '#aaa', fontSize: 14 },
  goodsSection: { backgroundColor: 'rgba(255,255,255,0.1)', borderRadius: 10, padding: 15, marginBottom: 15 },
  goodsItem: { width: 60, height: 60, backgroundColor: '#fff', borderRadius: 6, marginRight: 10, alignItems: 'center', justifyContent: 'center' },
  goodsImg: { width: 50, height: 50 },
  tracesSection: { backgroundColor: 'rgba(255,255,255,0.1)', borderRadius: 10, padding: 15 },
  tracesTitle: { color: '#fff', fontSize: 16, fontWeight: 'bold', marginBottom: 15 },
  traceItem: { flexDirection: 'row', position: 'relative', paddingLeft: 20, marginBottom: 15 },
  traceDot: { position: 'absolute', left: 0, top: 6, width: 10, height: 10, borderRadius: 5, backgroundColor: '#FC7D2E' },
  traceLine: { position: 'absolute', left: 4, top: 16, width: 2, height: '100%', backgroundColor: 'rgba(255,255,255,0.2)' },
  traceContent: { flex: 1 },
  traceTime: { color: '#aaa', fontSize: 12, marginBottom: 4 },
  traceText: { color: '#fff', fontSize: 14 },
  noTraces: { marginTop: 20, alignItems: 'center' },
  noTracesText: { color: '#999', fontSize: 14 },
});
