/**
 * CreateTradeScreen 发布/编辑商品（现代化扁平风格）
 * 设计风格：
 * - 纯白背景，扁平化设计
 * - 灰色填充输入框，圆角14px
 * - 橙色圆角按钮
 * - 清晰的标签 + 输入框分组
 * - 与登录、注册、创建群聊保持一致
 */

import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
import {
  View,
  TextInput,
  ScrollView,
  Alert,
  TouchableOpacity,
  Image,
  StyleSheet,
  Pressable,
  KeyboardAvoidingView,
  Platform,
  Animated,
  ActivityIndicator,
} from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { Loading } from '../../components/common';
import { SafeAreaView } from 'react-native-safe-area-context';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useAppColors, type AppColors } from '../../theme';
import { Text } from '../../components/common';
import { tradeService } from '../../services/trade/tradeService';
import { uploadService } from '../../services';
import type { TradeType, TradeCategory, TradeCondition, TradeItemDetailDTO } from '../../types/trade';
import { ALL_TRADE_CATEGORIES, ALL_TRADE_CONDITIONS } from '../../types/trade';

interface CreateTradeScreenProps {
  onClose: () => void;
  onSuccess?: () => void;
  editItem?: TradeItemDetailDTO;
}

function createStyles(colors: AppColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background.paper,
    },
    keyboardView: {
      flex: 1,
    },
    scrollContent: {
      flexGrow: 1,
      paddingHorizontal: 28,
      paddingTop: 20,
      paddingBottom: 40,
    },
    content: {
      flex: 1,
      maxWidth: 400,
      width: '100%',
      alignSelf: 'center',
    },

    // 标题区域
    titleSection: {
      marginBottom: 32,
      marginTop: 12,
    },
    title: {
      fontSize: 28,
      fontWeight: '700',
      color: colors.text.primary,
      lineHeight: 36,
    },
    underline: {
      width: 40,
      height: 4,
      backgroundColor: colors.primary.main,
      borderRadius: 2,
      marginTop: 12,
      marginBottom: 12,
    },
    subtitle: {
      fontSize: 15,
      color: colors.text.secondary,
    },

    // 输入框区域（参考登录注册风格）
    inputContainer: {
      marginBottom: 24,
    },
    inputLabel: {
      fontSize: 14,
      fontWeight: '500',
      color: colors.text.secondary,
      marginBottom: 10,
    },
    requiredMark: {
      color: colors.error.main,
      fontWeight: '600',
    },
    inputWrapper: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: colors.background.default,
      borderRadius: 14,
      paddingHorizontal: 18,
      minHeight: 56,
      borderWidth: 1,
      borderColor: 'transparent',
    },
    input: {
      flex: 1,
      fontSize: 16,
      color: colors.text.primary,
      minHeight: 56,
    },
    textAreaWrapper: {
      paddingVertical: 14,
      alignItems: 'flex-start',
    },
    textArea: {
      minHeight: 100,
      lineHeight: 22,
      textAlignVertical: 'top',
    },
    checkIcon: {
      marginLeft: 8,
    },
    charCount: {
      textAlign: 'right',
      marginTop: 6,
      fontSize: 12,
      color: colors.text.hint,
      fontWeight: '500',
    },

    // 交易类型选择
    typeRow: {
      flexDirection: 'row',
      gap: 12,
    },
    typeButton: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      gap: 8,
      paddingVertical: 14,
      borderRadius: 14,
      borderWidth: 1,
      borderColor: colors.divider,
      backgroundColor: colors.background.default,
    },
    typeButtonActive: {
      borderColor: colors.primary.main,
      backgroundColor: `${colors.primary.main}12`,
    },
    typeButtonText: {
      fontSize: 16,
      color: colors.text.secondary,
    },
    typeButtonTextActive: {
      color: colors.primary.main,
      fontWeight: '600',
    },

    // 分类/成色选项（紧凑横向滚动）
    optionRow: {
      flexDirection: 'row',
      gap: 8,
    },
    optionChip: {
      paddingHorizontal: 14,
      paddingVertical: 8,
      borderRadius: 10,
      backgroundColor: colors.background.default,
      borderWidth: 1,
      borderColor: colors.divider,
    },
    optionChipActive: {
      borderColor: colors.primary.main,
      backgroundColor: `${colors.primary.main}12`,
    },
    optionChipText: {
      fontSize: 13,
      color: colors.text.secondary,
    },
    optionChipTextActive: {
      color: colors.primary.main,
      fontWeight: '600',
    },

    // 价格输入
    priceInputWrapper: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: colors.background.default,
      borderRadius: 14,
      paddingHorizontal: 18,
      minHeight: 56,
      borderWidth: 1,
      borderColor: 'transparent',
    },
    pricePrefix: {
      fontSize: 18,
      color: colors.text.hint,
      marginRight: 4,
    },
    priceField: {
      flex: 1,
      fontSize: 16,
      color: colors.text.primary,
      minHeight: 56,
    },

    // 图片上传
    imageSection: {
      marginBottom: 24,
    },
    imageGrid: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: 10,
    },
    imageItem: {
      width: 100,
      height: 100,
      borderRadius: 14,
      overflow: 'hidden',
      position: 'relative',
    },
    imagePreview: {
      width: '100%',
      height: '100%',
      resizeMode: 'cover',
    },
    removeImageBtn: {
      position: 'absolute',
      top: 6,
      right: 6,
      width: 24,
      height: 24,
      borderRadius: 12,
      backgroundColor: 'rgba(0,0,0,0.5)',
      alignItems: 'center',
      justifyContent: 'center',
    },
    addImageBtn: {
      width: 100,
      height: 100,
      borderRadius: 14,
      borderWidth: 2,
      borderColor: colors.divider,
      borderStyle: 'dashed',
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: colors.background.default,
    },
    uploadingOverlay: {
      ...StyleSheet.absoluteFillObject,
      backgroundColor: 'rgba(0,0,0,0.3)',
      alignItems: 'center',
      justifyContent: 'center',
      borderRadius: 14,
    },

    // 提交按钮
    submitBtn: {
      height: 56,
      borderRadius: 14,
      backgroundColor: colors.primary.main,
      alignItems: 'center',
      justifyContent: 'center',
      marginTop: 8,
      marginBottom: 16,
    },
    submitBtnDisabled: {
      opacity: 0.6,
    },
    submitBtnText: {
      fontSize: 17,
      fontWeight: '600',
      color: colors.text.inverse,
    },

    // 顶部关闭按钮
    header: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      paddingHorizontal: 16,
      paddingVertical: 12,
    },
    backIconButton: {
      width: 40,
      height: 40,
      alignItems: 'center',
      justifyContent: 'center',
    },
    headerTitle: {
      fontSize: 18,
      fontWeight: '600',
      color: colors.text.primary,
    },
    headerRight: {
      width: 40,
    },
  });
}

export function CreateTradeScreen({ onClose, onSuccess, editItem }: CreateTradeScreenProps) {
  const colors = useAppColors();
  const styles = useMemo(() => createStyles(colors), [colors]);
  const isEdit = !!editItem;

  const [tradeType, setTradeType] = useState<TradeType>(editItem?.trade_type || 'sell');
  const [category, setCategory] = useState<TradeCategory>(editItem?.category || 'digital');
  const [title, setTitle] = useState(editItem?.title || '');
  const [content, setContent] = useState(editItem?.content || '');
  const [price, setPrice] = useState(editItem?.price != null ? String(editItem.price) : '');
  const [condition, setCondition] = useState<TradeCondition | undefined>(
    editItem?.condition as TradeCondition | undefined
  );
  const [images, setImages] = useState<{ uri: string; uploading: boolean }[]>(
    editItem?.images?.map(img => ({ uri: img.url, uploading: false })) || []
  );
  const [submitting, setSubmitting] = useState(false);

  // 动画值
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(20)).current;

  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 400,
        useNativeDriver: true,
      }),
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 400,
        useNativeDriver: true,
      }),
    ]).start();
  }, []);

  const handleSubmit = useCallback(async () => {
    if (!title.trim()) {
      Alert.alert('提示', '请输入标题');
      return;
    }
    if (images.some(img => img.uploading)) {
      Alert.alert('提示', '请等待图片上传完成');
      return;
    }

    setSubmitting(true);
    try {
      const payload = {
        trade_type: tradeType,
        category,
        title: title.trim(),
        content: content.trim() || title.trim(),
        images: images.map(img => img.uri),
        price: price ? parseFloat(price) : null,
        condition,
      };

      if (isEdit && editItem) {
        await tradeService.updateTradeItem(editItem.id, payload);
      } else {
        await tradeService.createTradeItem(payload);
      }
      onSuccess?.();
      onClose();
    } catch (e: any) {
      Alert.alert(isEdit ? '更新失败' : '发布失败', e?.message || '请稍后重试');
    } finally {
      setSubmitting(false);
    }
  }, [title, content, tradeType, category, price, condition, images, onClose, onSuccess, isEdit, editItem]);

  const handlePickImage = useCallback(async () => {
    if (images.length >= 9) {
      Alert.alert('提示', '最多上传9张图片');
      return;
    }

    const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (!permissionResult.granted) {
      Alert.alert('权限不足', '需要访问相册权限来选择图片');
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: 'images',
      allowsMultipleSelection: true,
      selectionLimit: 9 - images.length,
      quality: 1,
    });

    if (!result.canceled && result.assets) {
      const newImages = result.assets.map(asset => ({ uri: asset.uri, uploading: true }));
      setImages(prev => [...prev, ...newImages]);

      for (let i = 0; i < newImages.length; i++) {
        const asset = result.assets[i];
        const uploadResult = await uploadService.uploadImage({
          uri: asset.uri,
          type: asset.mimeType || 'image/jpeg',
        });

        if (uploadResult) {
          setImages(prev => {
            const updated = [...prev];
            const index = prev.findIndex(img => img.uri === asset.uri);
            if (index !== -1) {
              updated[index] = { uri: uploadResult.url, uploading: false };
            }
            return updated;
          });
        } else {
          setImages(prev => prev.filter(img => img.uri !== asset.uri));
        }
      }
    }
  }, [images.length]);

  const removeImage = useCallback((uri: string) => {
    setImages(prev => prev.filter(img => img.uri !== uri));
  }, []);

  const canSubmit = title.trim().length > 0 && !submitting && !images.some(i => i.uploading);

  return (
    <SafeAreaView style={styles.container} edges={['top', 'bottom']}>
      {/* 顶部导航 */}
      <View style={styles.header}>
        <TouchableOpacity onPress={onClose} style={styles.backIconButton} activeOpacity={0.8}>
          <MaterialCommunityIcons name="close" size={24} color={colors.text.primary} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>{isEdit ? '编辑商品' : '发布商品'}</Text>
        <View style={styles.headerRight} />
      </View>

      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardView}
      >
        <ScrollView
          contentContainerStyle={styles.scrollContent}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
        >
          <Animated.View
            style={[
              styles.content,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            {/* 标题区域 */}
            <View style={styles.titleSection}>
              <Text style={styles.title}>{isEdit ? '编辑' + (tradeType === 'buy' ? '收购' : '商品') : '发布' + (tradeType === 'buy' ? '收购' : '商品')}</Text>
              <View style={styles.underline} />
              <Text style={styles.subtitle}>{tradeType === 'buy' ? '填写收购需求，让卖家主动联系你' : '填写商品信息，让更多人看到'}</Text>
            </View>

            {/* 交易类型 */}
            <View style={styles.inputContainer}>
              <Text style={styles.inputLabel}>交易类型</Text>
              <View style={styles.typeRow}>
                <Pressable
                  style={[styles.typeButton, tradeType === 'sell' && styles.typeButtonActive]}
                  onPress={() => setTradeType('sell')}
                >
                  <MaterialCommunityIcons name="tag-outline" size={18} color={tradeType === 'sell' ? colors.primary.main : colors.text.hint} />
                  <Text style={[styles.typeButtonText, tradeType === 'sell' ? styles.typeButtonTextActive : {}]}>出售</Text>
                </Pressable>
                <Pressable
                  style={[styles.typeButton, tradeType === 'buy' && styles.typeButtonActive]}
                  onPress={() => setTradeType('buy')}
                >
                  <MaterialCommunityIcons name="hand-coin-outline" size={18} color={tradeType === 'buy' ? colors.primary.main : colors.text.hint} />
                  <Text style={[styles.typeButtonText, tradeType === 'buy' ? styles.typeButtonTextActive : {}]}>收购</Text>
                </Pressable>
              </View>
            </View>

            {/* 分类 */}
            <View style={styles.inputContainer}>
              <Text style={styles.inputLabel}>分类</Text>
              <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                <View style={styles.optionRow}>
                  {ALL_TRADE_CATEGORIES.map(cat => (
                    <Pressable
                      key={cat.key}
                      style={[styles.optionChip, category === cat.key && styles.optionChipActive]}
                      onPress={() => setCategory(cat.key)}
                    >
                      <Text style={[styles.optionChipText, category === cat.key ? styles.optionChipTextActive : {}]}>
                        {cat.label}
                      </Text>
                    </Pressable>
                  ))}
                </View>
              </ScrollView>
            </View>

            {/* 标题 */}
            <View style={styles.inputContainer}>
              <Text style={styles.inputLabel}>标题 <Text style={styles.requiredMark}>*</Text></Text>
              <View style={styles.inputWrapper}>
                <TextInput
                  style={styles.input}
                  value={title}
                  onChangeText={setTitle}
                  placeholder={tradeType === 'buy' ? '描述你想收购的商品' : '描述你的商品'}
                  placeholderTextColor={colors.text.hint}
                  maxLength={100}
                  cursorColor={colors.primary.main}
                  selectionColor={`${colors.primary.main}40`}
                />
                {title.length > 0 && (
                  <MaterialCommunityIcons name="check-circle" size={20} color={colors.primary.main} style={styles.checkIcon} />
                )}
              </View>
              <Text style={styles.charCount}>{title.length}/100</Text>
            </View>

            {/* 描述 */}
            <View style={styles.inputContainer}>
              <Text style={styles.inputLabel}>描述</Text>
              <View style={[styles.inputWrapper, styles.textAreaWrapper]}>
                <TextInput
                  style={[styles.input, styles.textArea]}
                  value={content}
                  onChangeText={setContent}
                  placeholder={tradeType === 'buy' ? '详细描述收购需求、预算、成色要求等...' : '详细描述商品情况...'}
                  placeholderTextColor={colors.text.hint}
                  multiline
                  maxLength={2000}
                  textAlignVertical="top"
                  cursorColor={colors.primary.main}
                  selectionColor={`${colors.primary.main}40`}
                />
              </View>
              <Text style={styles.charCount}>{content.length}/2000</Text>
            </View>

            {/* 图片 */}
            <View style={styles.imageSection}>
              <Text style={styles.inputLabel}>图片 ({images.length}/9)</Text>
              <View style={styles.imageGrid}>
                {images.map((img) => (
                  <View key={img.uri} style={styles.imageItem}>
                    <Image source={{ uri: img.uri.startsWith('http') ? img.uri : img.uri }} style={styles.imagePreview} />
                    {img.uploading && (
                      <View style={styles.uploadingOverlay}>
                        <Loading size="sm" />
                      </View>
                    )}
                    <Pressable style={styles.removeImageBtn} onPress={() => removeImage(img.uri)}>
                      <MaterialCommunityIcons name="close" size={16} color="#fff" />
                    </Pressable>
                  </View>
                ))}
                {images.length < 9 && (
                  <Pressable style={styles.addImageBtn} onPress={handlePickImage}>
                    <MaterialCommunityIcons name="plus" size={32} color={colors.text.hint} />
                    <Text style={{ fontSize: 12, color: colors.text.hint, marginTop: 4 }}>添加图片</Text>
                  </Pressable>
                )}
              </View>
            </View>

            {/* 价格 */}
            <View style={styles.inputContainer}>
              <Text style={styles.inputLabel}>价格（留空为面议）</Text>
              <View style={styles.priceInputWrapper}>
                <Text style={styles.pricePrefix}>¥</Text>
                <TextInput
                  style={styles.priceField}
                  value={price}
                  onChangeText={setPrice}
                  placeholder="请输入价格"
                  placeholderTextColor={colors.text.hint}
                  keyboardType="decimal-pad"
                  maxLength={10}
                  cursorColor={colors.primary.main}
                />
              </View>
            </View>

            {/* 成色 */}
            {tradeType === 'sell' && (
              <View style={styles.inputContainer}>
                <Text style={styles.inputLabel}>成色</Text>
                <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                  <View style={styles.optionRow}>
                    {ALL_TRADE_CONDITIONS.map(c => (
                      <Pressable
                        key={c.key}
                        style={[styles.optionChip, condition === c.key && styles.optionChipActive]}
                        onPress={() => setCondition(condition === c.key ? undefined : c.key)}
                      >
                        <Text style={[styles.optionChipText, condition === c.key ? styles.optionChipTextActive : {}]}>
                          {c.label}
                        </Text>
                      </Pressable>
                    ))}
                  </View>
                </ScrollView>
              </View>
            )}

            {/* 提交按钮 */}
            <TouchableOpacity
              style={[styles.submitBtn, !canSubmit && styles.submitBtnDisabled]}
              onPress={handleSubmit}
              disabled={!canSubmit}
              activeOpacity={0.9}
            >
              {submitting ? (
                <ActivityIndicator size="small" color={colors.text.inverse} />
              ) : (
                <Text style={styles.submitBtnText}>{isEdit ? '保存' : '发布'}</Text>
              )}
            </TouchableOpacity>
          </Animated.View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}
