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

import { Images } from '@/constants/images';
import { Address, getDefaultAddress } from '@/services/address';
import { takeApply, takePreview } from '@/services/award';

interface GroupedGoods {
  total: number;
  data: { id: string; cover: string; spuId: string; level: string };
}

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

  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [address, setAddress] = useState<Address | null>(null);
  const [expressAmount, setExpressAmount] = useState(0);
  const [goodsList, setGoodsList] = useState<GroupedGoods[]>([]);
  const [inventoryIds, setInventoryIds] = useState<string[]>([]);

  const showAlert = (msg: string) => {
    if (Platform.OS === 'web') window.alert(msg);
    else Alert.alert('提示', msg);
  };

  const loadData = useCallback(async () => {
    if (!ids) return;
    setLoading(true);
    try {
      const idList = ids.split(',');
      setInventoryIds(idList);
      
      // 获取默认地址
      const addr = await getDefaultAddress();
      setAddress(addr);
      
      // 获取提货预览
      const res = await takePreview(idList, addr?.id || '');
      if (res) {
        setExpressAmount(res.expressAmount || 0);
        // 合并相同商品
        const goodsMap: Record<string, GroupedGoods> = {};
        (res.itemList || []).forEach((item: any) => {
          const key = `${item.spuId}_${item.level}`;
          if (goodsMap[key]) {
            goodsMap[key].total += 1;
          } else {
            goodsMap[key] = { total: 1, data: item };
          }
        });
        setGoodsList(Object.values(goodsMap));
      }
    } catch (e) {
      console.error('加载提货信息失败:', e);
    }
    setLoading(false);
  }, [ids]);

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

  const goToAddress = () => {
    router.push('/address?type=1' as any);
  };

  const handleSubmit = async () => {
    if (!address) {
      showAlert('请选择收货地址');
      return;
    }
    if (submitting) return;
    setSubmitting(true);
    try {
      const res = await takeApply(inventoryIds, address.id, 'ALIPAY_H5');
      if (res) {
        showAlert('提货成功');
        router.back();
      }
    } catch (e) {
      console.error('提货失败:', e);
    }
    setSubmitting(false);
  };

  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}>
          {/* 商品列表 */}
          <View style={styles.goodsSection}>
            <ScrollView horizontal showsHorizontalScrollIndicator={false}>
              {goodsList.map((goods, idx) => (
                <View key={idx} style={styles.goodsItem}>
                  <Image source={{ uri: goods.data.cover }} style={styles.goodsImg} contentFit="contain" />
                  <View style={styles.goodsCount}>
                    <Text style={styles.goodsCountText}>x{goods.total}</Text>
                  </View>
                </View>
              ))}
            </ScrollView>
          </View>

          {/* 运费 */}
          <View style={styles.feeRow}>
            <Text style={styles.feeLabel}>运费</Text>
            <Text style={styles.feeValue}>¥{expressAmount}</Text>
          </View>

          {/* 收货地址 */}
          <TouchableOpacity style={styles.addressSection} onPress={goToAddress}>
            {!address ? (
              <Text style={styles.noAddress}>请填写收货地址</Text>
            ) : (
              <View style={styles.addressInfo}>
                <Text style={styles.addressName}>{address.contactName} {address.contactNo}</Text>
                <Text style={styles.addressDetail}>{address.province}{address.city}{address.district}{address.address}</Text>
              </View>
            )}
            <Text style={styles.arrowIcon}>›</Text>
          </TouchableOpacity>
        </ScrollView>

        {/* 底部按钮 */}
        <View style={[styles.bottomBar, { paddingBottom: insets.bottom + 10 }]}>
          <TouchableOpacity style={styles.submitBtn} onPress={handleSubmit} disabled={submitting}>
            <ImageBackground source={{ uri: Images.common.loginBtn }} style={styles.submitBtnBg} resizeMode="contain">
              <Text style={styles.submitBtnText}>{submitting ? '提交中...' : '确定发货'}</Text>
            </ImageBackground>
          </TouchableOpacity>
        </View>
      </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 },
  goodsSection: { backgroundColor: 'rgba(255,255,255,0.1)', borderRadius: 10, padding: 15, marginBottom: 15 },
  goodsItem: { width: 79, height: 103, backgroundColor: '#fff', borderRadius: 6, marginRight: 10, alignItems: 'center', justifyContent: 'center', position: 'relative', borderWidth: 1, borderColor: '#eaeaea' },
  goodsImg: { width: 73, height: 85 },
  goodsCount: { position: 'absolute', top: 0, right: 0, backgroundColor: '#ff6b00', borderRadius: 2, paddingHorizontal: 4, paddingVertical: 2 },
  goodsCountText: { color: '#fff', fontSize: 10, fontWeight: 'bold' },
  feeRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', backgroundColor: 'rgba(255,255,255,0.1)', borderRadius: 10, padding: 15, marginBottom: 15 },
  feeLabel: { color: '#fff', fontSize: 14 },
  feeValue: { color: '#ff6b00', fontSize: 16, fontWeight: 'bold' },
  addressSection: { flexDirection: 'row', alignItems: 'center', backgroundColor: 'rgba(255,255,255,0.1)', borderRadius: 10, padding: 15, marginBottom: 15 },
  noAddress: { flex: 1, color: '#fff', fontSize: 16, fontWeight: 'bold' },
  addressInfo: { flex: 1 },
  addressName: { color: '#fff', fontSize: 14, fontWeight: 'bold' },
  addressDetail: { color: '#aaa', fontSize: 12, marginTop: 4 },
  arrowIcon: { color: '#fff', fontSize: 20, marginLeft: 10 },
  bottomBar: { paddingHorizontal: 15, paddingTop: 10 },
  submitBtn: { alignItems: 'center' },
  submitBtnBg: { width: 260, height: 60, justifyContent: 'center', alignItems: 'center' },
  submitBtnText: { color: '#000', fontSize: 16, fontWeight: 'bold' },
});
