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

import { getPoolDetail } from '@/services/award';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

interface ProductItem {
  id: string;
  name: string;
  cover: string;
  level: string;
  probability: number;
  quantity?: number;
  spu?: {
    id: string;
    cover: string;
    name: string;
    marketPrice?: number;
    parameter?: string;
    brandName?: string;
    worksName?: string;
    pic?: string;
  };
}

interface PoolData {
  id: string;
  name: string;
  price: number;
  luckGoodsList: ProductItem[];
  recommendedLuckPool?: any[];
}

export default function AwardDetailSwipeScreen() {
  const { poolId, index } = useLocalSearchParams<{ poolId: string; index: string }>();
  const router = useRouter();
  const insets = useSafeAreaInsets();

  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<PoolData | null>(null);
  const [products, setProducts] = useState<ProductItem[]>([]);
  const [currentIndex, setCurrentIndex] = useState(parseInt(index || '0', 10));

  const loadData = useCallback(async () => {
    if (!poolId) return;
    setLoading(true);
    try {
      const detail = await getPoolDetail(poolId);
      if (detail) {
        setData(detail);
        setProducts(detail.luckGoodsList || []);
      }
    } catch (error) {
      console.error('加载数据失败:', error);
    }
    setLoading(false);
  }, [poolId]);

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

  const handlePrev = () => {
    if (currentIndex > 0) setCurrentIndex(currentIndex - 1);
  };

  const handleNext = () => {
    if (currentIndex < products.length - 1) setCurrentIndex(currentIndex + 1);
  };

  const parseParameter = (paramStr?: string) => {
    if (!paramStr) return [];
    try {
      return JSON.parse(paramStr);
    } catch {
      return [];
    }
  };

  if (loading) {
    return (
      <View style={[styles.loadingContainer, { paddingTop: insets.top }]}>
        <ActivityIndicator size="large" color="#ff6600" />
      </View>
    );
  }

  if (!data || products.length === 0) {
    return (
      <View style={[styles.loadingContainer, { paddingTop: insets.top }]}>
        <Text style={styles.errorText}>商品不存在</Text>
        <TouchableOpacity style={styles.backBtn2} onPress={() => router.back()}>
          <Text style={styles.backBtn2Text}>返回</Text>
        </TouchableOpacity>
      </View>
    );
  }

  const currentProduct = products[currentIndex];
  const params = parseParameter(currentProduct?.spu?.parameter);
  const detailPics = currentProduct?.spu?.pic ? currentProduct.spu.pic.split(',').filter(Boolean) : [];
  const recommendList = data.recommendedLuckPool || [];

  return (
    <View style={styles.container}>
      <StatusBar barStyle="dark-content" />
      
      {/* 顶部导航 */}
      <View style={[styles.header, { paddingTop: insets.top }]}>
        <TouchableOpacity style={styles.backBtn} onPress={() => router.back()}>
          <Text style={styles.backText}>{'<'}</Text>
        </TouchableOpacity>
        <View style={styles.placeholder} />
      </View>

      <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
        {/* 商品图片区域 */}
        <View style={styles.imageSection}>
          <Image
            source={{ uri: currentProduct?.spu?.cover || currentProduct?.cover }}
            style={styles.productImage}
            contentFit="contain"
          />

          {/* 左右切换按钮 */}
          {currentIndex > 0 && (
            <TouchableOpacity style={styles.prevBtn} onPress={handlePrev}>
              <Text style={styles.arrowText}>{'<'}</Text>
            </TouchableOpacity>
          )}
          {currentIndex < products.length - 1 && (
            <TouchableOpacity style={styles.nextBtn} onPress={handleNext}>
              <Text style={styles.arrowText}>{'>'}</Text>
            </TouchableOpacity>
          )}
        </View>

        {/* 价格和名称区域 */}
        <View style={styles.priceSection}>
          <View style={styles.priceRow}>
            <Text style={styles.priceText}>¥{currentProduct?.spu?.marketPrice || data.price}</Text>
          </View>
          <Text style={styles.productName}>{currentProduct?.name}</Text>
        </View>

        {/* 参数区域 */}
        <View style={styles.paramSection}>
          <View style={styles.paramHeader}>
            <Text style={styles.paramTitle}>参数</Text>
          </View>
          {params.length > 0 && (
            <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.paramScroll}>
              {params.map((param: { label: string; value: string }, idx: number) => (
                <View key={idx} style={styles.paramItem}>
                  <Text style={styles.paramLabel}>{param.label}</Text>
                  <Text style={styles.paramValue}>{param.value}</Text>
                </View>
              ))}
            </ScrollView>
          )}
          {currentProduct?.spu?.worksName && (
            <View style={styles.paramRow}>
              <Text style={styles.paramRowLabel}>IP</Text>
              <Text style={styles.paramRowValue}>{currentProduct.spu.worksName}</Text>
            </View>
          )}
          {currentProduct?.spu?.brandName && (
            <View style={styles.paramRow}>
              <Text style={styles.paramRowLabel}>品牌</Text>
              <Text style={styles.paramRowValue}>{currentProduct.spu.brandName}</Text>
            </View>
          )}
        </View>

        {/* 放心购 正品保障 */}
        <View style={styles.guaranteeSection}>
          <Text style={styles.guaranteeTitle}>放心购  正品保障</Text>
          <Text style={styles.guaranteeText}>不支持七天无理由退换货 包邮</Text>
        </View>

        {/* 商品推荐 */}
        {recommendList.length > 0 && (
          <View style={styles.recommendSection}>
            <Text style={styles.recommendTitle}>商品推荐</Text>
            <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.recommendScroll}>
              {recommendList.map((item: any) => (
                <TouchableOpacity 
                  key={item.id} 
                  style={styles.recommendItem} 
                  activeOpacity={0.8}
                  onPress={() => router.push({ pathname: '/award-detail', params: { poolId: item.id } } as any)}
                >
                  <Image source={{ uri: item.cover }} style={styles.recommendImage} contentFit="contain" />
                  <Text style={styles.recommendName} numberOfLines={1}>{item.name}</Text>
                  <Text style={styles.recommendPrice}>¥{item.price}</Text>
                </TouchableOpacity>
              ))}
            </ScrollView>
          </View>
        )}

        {/* 商品详情 */}
        <View style={styles.detailSection}>
          <Text style={styles.detailTitle}>商品详情</Text>
          {detailPics.length > 0 ? (
            detailPics.map((pic, idx) => (
              <Image key={idx} source={{ uri: pic }} style={styles.detailImage} contentFit="contain" />
            ))
          ) : (
            <View style={styles.detailContent}>
              <Text style={styles.detailHeading}>商城购买须知！</Text>
              
              <Text style={styles.detailSubTitle}>商城现货</Text>
              <Text style={styles.detailText}>
                商城所售现货商品均为全新正版商品。手办模玩非艺术品，因厂商品控差异导致的微小瑕疵属于正常情况，官图仅供参考，具体以实物为准。
              </Text>
              
              <Text style={styles.detailSubTitle}>新品预定</Text>
              <Text style={styles.detailText}>
                预定商品的总价=定金+尾款，在预定期限内支付定金后，商品到货并补齐尾款后,超级商城才会发货相应商品预定订单确认成功后，定金不可退。{'\n'}
                商品页面显示的商品制作完成时间及预计补款时间，都是按照官方预估的时间推测，具体到货时间请以实际出货为准。如因厂商、海关等因素造成延期的，不接受以此原因申请定金退款，请耐心等待。
              </Text>
              
              <Text style={styles.detailSubTitle}>预售补款</Text>
              <Text style={styles.detailText}>
                商品到货后超级商城会通过您在预定时预留的号码进行短信通知请自行留意。为防止错过补款通知，可添加商城客服，并备注所购商品进入对应社群，社群会同步推送新品咨询及补款通知。
              </Text>
            </View>
          )}
        </View>

        <View style={{ height: 50 }} />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#f5f5f5' },
  loadingContainer: { flex: 1, backgroundColor: '#f5f5f5', justifyContent: 'center', alignItems: 'center' },
  errorText: { color: '#999', fontSize: 16 },
  backBtn2: { marginTop: 20, backgroundColor: '#ff6600', paddingHorizontal: 20, paddingVertical: 10, borderRadius: 8 },
  backBtn2Text: { color: '#fff', fontSize: 14 },

  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 10,
    paddingBottom: 10,
    backgroundColor: 'transparent',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    zIndex: 10,
  },
  backBtn: { width: 40, height: 40, justifyContent: 'center', alignItems: 'center' },
  backText: { color: '#333', fontSize: 24, fontWeight: 'bold' },
  placeholder: { width: 40 },

  scrollView: { flex: 1 },

  // 图片区域
  imageSection: {
    paddingTop: 80,
    paddingBottom: 20,
    alignItems: 'center',
    position: 'relative',
  },
  productImage: {
    width: SCREEN_WIDTH * 0.7,
    height: 350,
  },
  prevBtn: {
    position: 'absolute',
    left: 10,
    top: '50%',
    width: 36,
    height: 36,
    backgroundColor: 'rgba(0,0,0,0.3)',
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
  },
  nextBtn: {
    position: 'absolute',
    right: 10,
    top: '50%',
    width: 36,
    height: 36,
    backgroundColor: 'rgba(0,0,0,0.3)',
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
  },
  arrowText: { color: '#fff', fontSize: 18, fontWeight: 'bold' },

  // 价格区域
  priceSection: {
    backgroundColor: '#fff',
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  priceRow: {
    flexDirection: 'row',
    alignItems: 'baseline',
  },
  priceText: {
    fontSize: 24,
    color: '#ff4444',
    fontWeight: 'bold',
  },
  productName: {
    fontSize: 16,
    color: '#333',
    marginTop: 8,
    lineHeight: 22,
  },

  // 参数区域
  paramSection: {
    backgroundColor: '#fff',
    marginTop: 10,
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  paramHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingBottom: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  paramTitle: {
    fontSize: 14,
    color: '#666',
  },
  paramScroll: {
    marginTop: 10,
  },
  paramItem: {
    paddingHorizontal: 12,
    borderRightWidth: 1,
    borderRightColor: '#eee',
  },
  paramLabel: { fontSize: 14, color: '#666' },
  paramValue: { fontSize: 14, color: '#333', marginTop: 4 },
  paramRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingTop: 12,
  },
  paramRowLabel: {
    fontSize: 14,
    color: '#666',
    width: 50,
  },
  paramRowValue: {
    fontSize: 14,
    color: '#333',
    flex: 1,
  },

  // 放心购区域
  guaranteeSection: {
    backgroundColor: '#fff',
    marginTop: 10,
    paddingHorizontal: 16,
    paddingVertical: 12,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  guaranteeTitle: {
    fontSize: 14,
    color: '#333',
    fontWeight: 'bold',
  },
  guaranteeText: {
    fontSize: 12,
    color: '#999',
  },

  // 商品推荐
  recommendSection: {
    backgroundColor: '#1a1a1a',
    marginTop: 10,
    paddingHorizontal: 16,
    paddingVertical: 16,
  },
  recommendTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 12,
  },
  recommendScroll: {
    paddingRight: 10,
  },
  recommendItem: {
    width: 90,
    marginRight: 12,
  },
  recommendImage: {
    width: 90,
    height: 90,
    backgroundColor: '#fff',
    borderRadius: 4,
  },
  recommendName: {
    fontSize: 12,
    color: '#fff',
    marginTop: 6,
  },
  recommendPrice: {
    fontSize: 14,
    color: '#ff4444',
    fontWeight: 'bold',
    marginTop: 4,
  },

  // 商品详情
  detailSection: {
    backgroundColor: '#1a1a1a',
    marginTop: 10,
    paddingHorizontal: 16,
    paddingVertical: 16,
  },
  detailTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 16,
  },
  detailImage: {
    width: SCREEN_WIDTH - 32,
    height: 400,
    marginBottom: 10,
  },
  detailContent: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 16,
  },
  detailHeading: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    textAlign: 'center',
    marginBottom: 20,
  },
  detailSubTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginTop: 16,
    marginBottom: 8,
    paddingLeft: 10,
    borderLeftWidth: 3,
    borderLeftColor: '#333',
  },
  detailText: {
    fontSize: 14,
    color: '#666',
    lineHeight: 22,
  },
});
