import { useRouter } from 'expo-router';
import React, { useState } from 'react';
import {
    Alert,
    ImageBackground,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { Images } from '@/constants/images';
import { submitFeedback } from '@/services/base';

const FEEDBACK_TYPES = ['BUG', '建议', '投诉', '其他'];

export default function FeedbackScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const [feedbackType, setFeedbackType] = useState('BUG');
  const [feedbackContent, setFeedbackContent] = useState('');
  const [loading, setLoading] = useState(false);
  const maxContentLength = 3000;

  const handleBack = () => {
    router.back();
  };

  const handleSubmit = async () => {
    if (!feedbackContent.trim()) {
      Alert.alert('提示', '反馈内容是必填的！');
      return;
    }

    try {
      setLoading(true);
      await submitFeedback({
        type: feedbackType,
        text: feedbackContent.trim(),
      });
      
      Alert.alert('提示', '提交成功！', [
        { text: '确定', onPress: () => router.back() }
      ]);
    } catch (error) {
      console.error('提交失败:', error);
      Alert.alert('提示', '提交失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <ImageBackground
      source={{ uri: Images.mine.kaixinMineBg }}
      style={styles.container}
      resizeMode="cover"
    >
      <StatusBar barStyle="light-content" />
      
      {/* 顶部导航 */}
      <View style={[styles.header, { paddingTop: insets.top }]}>
        <TouchableOpacity style={styles.backBtn} onPress={handleBack}>
          <Text style={styles.backIcon}>‹</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>意见反馈</Text>
        <View style={styles.placeholder} />
      </View>

      <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
        <View style={styles.content}>
          <View style={styles.card}>
            {/* 类型选择 */}
            <View style={styles.typeSelector}>
              {FEEDBACK_TYPES.map((type) => (
                <TouchableOpacity
                  key={type}
                  style={[
                    styles.typeItem,
                    feedbackType === type && styles.typeItemActive
                  ]}
                  onPress={() => setFeedbackType(type)}
                >
                  <Text style={[
                    styles.typeText,
                    feedbackType === type && styles.typeTextActive
                  ]}>
                    {type}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>

            {/* 投诉提示 */}
            <View style={styles.complaintTip}>
              <Text style={styles.complaintTipText}>
                此投诉为本平台自有投诉渠道
              </Text>
            </View>

            {/* 输入框 */}
            <View style={styles.inputWrapper}>
              <TextInput
                style={styles.input}
                value={feedbackContent}
                onChangeText={setFeedbackContent}
                placeholder="请输入您的反馈内容，我们将及时为您处理。"
                placeholderTextColor="#999"
                multiline
                maxLength={maxContentLength}
              />
              <View style={styles.inputCount}>
                <Text style={[
                  styles.countNum,
                  feedbackContent.length > 0 && styles.countNumActive
                ]}>
                  {feedbackContent.length}
                </Text>
                <Text style={styles.countText}>/{maxContentLength}</Text>
              </View>
            </View>

            {/* 提交按钮 */}
            <TouchableOpacity
              style={styles.submitBtn}
              onPress={handleSubmit}
              disabled={loading}
            >
              <Text style={styles.submitBtnText}>
                {loading ? '提交中...' : '提交'}
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </ScrollView>
    </ImageBackground>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 10,
    height: 80,
  },
  backBtn: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  backIcon: {
    fontSize: 32,
    color: '#fff',
    fontWeight: 'bold',
  },
  headerTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#fff',
  },
  placeholder: {
    width: 40,
  },
  scrollView: {
    flex: 1,
  },
  content: {
    paddingHorizontal: 15,
    paddingTop: 10,
    paddingBottom: 30,
  },
  card: {
    backgroundColor: '#fff',
    borderRadius: 15,
    padding: 15,
  },
  typeSelector: {
    flexDirection: 'row',
    marginBottom: 10,
  },
  typeItem: {
    paddingHorizontal: 15,
    paddingVertical: 8,
    marginRight: 10,
    borderRadius: 20,
    backgroundColor: '#f8f8f8',
  },
  typeItemActive: {
    backgroundColor: '#FC7D2E',
  },
  typeText: {
    fontSize: 14,
    color: '#666',
  },
  typeTextActive: {
    color: '#fff',
  },
  complaintTip: {
    backgroundColor: '#fff7e6',
    borderWidth: 1,
    borderColor: '#ffd591',
    borderRadius: 4,
    padding: 10,
    marginBottom: 15,
  },
  complaintTipText: {
    fontSize: 13,
    color: '#fa8c16',
  },
  inputWrapper: {
    position: 'relative',
    marginBottom: 20,
  },
  input: {
    height: 150,
    backgroundColor: '#f8f8f8',
    borderRadius: 8,
    padding: 12,
    fontSize: 14,
    color: '#333',
    textAlignVertical: 'top',
  },
  inputCount: {
    position: 'absolute',
    bottom: 10,
    right: 10,
    flexDirection: 'row',
  },
  countNum: {
    fontSize: 12,
    color: '#999',
  },
  countNumActive: {
    color: '#1FA4FF',
  },
  countText: {
    fontSize: 12,
    color: '#999',
  },
  submitBtn: {
    backgroundColor: '#FC7D2E',
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
    alignItems: 'center',
  },
  submitBtnText: {
    fontSize: 16,
    color: '#fff',
    fontWeight: '500',
  },
});
