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

import { Images } from '@/constants/images';
import { harryExchange } from '@/services/award';

export default function ExchangeScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);

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

  const handleSubmit = async () => {
    if (!code.trim()) {
      Alert.alert('提示', '请输入兑换码');
      return;
    }

    try {
      setLoading(true);
      const res = await harryExchange({ code: code.trim() });
      
      if (res?.success) {
        let rewardType = '';
        const data = res.data;
        
        switch (data?.rewardType) {
          case 'USER_CREDIT':
            rewardType = '积分';
            break;
          case 'CASH':
            rewardType = '现金';
            break;
          case 'MAGIC':
            rewardType = '果实';
            break;
          case 'MAGIC_POWER_COIN':
            rewardType = '源力币';
            break;
          case 'COUPON':
            rewardType = '优惠券';
            break;
          case 'SPU_ID':
            rewardType = '商品';
            break;
          default:
            rewardType = '奖励';
        }

        const text = data?.rewardType === 'COUPON' || data?.rewardType === 'SPU_ID'
          ? `成功获得${rewardType}`
          : `成功获得${rewardType}${data?.rewardAmount || ''}`;

        Alert.alert('提示', text, [
          { text: '确定', onPress: () => router.back() }
        ]);
        setCode('');
      } else {
        Alert.alert('提示', res?.msg || '兑换失败');
      }
    } 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>

      <View style={styles.content}>
        <View style={styles.card}>
          <Text style={styles.describe}>请在下方输入您的兑换码</Text>
          
          <View style={styles.inputWrapper}>
            <TextInput
              style={styles.input}
              value={code}
              onChangeText={setCode}
              placeholder="请输入兑换码"
              placeholderTextColor="#999"
              multiline
            />
          </View>

          <View style={styles.btnsWrapper}>
            <TouchableOpacity 
              style={[styles.btn, styles.cancelBtn]} 
              onPress={handleBack}
            >
              <Text style={styles.cancelBtnText}>取消</Text>
            </TouchableOpacity>
            <TouchableOpacity 
              style={[styles.btn, styles.confirmBtn]} 
              onPress={handleSubmit}
              disabled={loading}
            >
              <Text style={styles.confirmBtnText}>
                {loading ? '兑换中...' : '确定'}
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </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,
  },
  content: {
    flex: 1,
    paddingHorizontal: 15,
    paddingTop: 20,
  },
  card: {
    backgroundColor: '#fff',
    borderRadius: 15,
    padding: 20,
  },
  describe: {
    fontSize: 14,
    color: '#333',
    marginBottom: 15,
    textAlign: 'center',
  },
  inputWrapper: {
    backgroundColor: '#f5f5f5',
    borderRadius: 8,
    padding: 10,
    marginBottom: 20,
  },
  input: {
    height: 80,
    fontSize: 16,
    color: '#333',
    textAlignVertical: 'top',
  },
  btnsWrapper: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  btn: {
    width: '45%',
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
    alignItems: 'center',
  },
  cancelBtn: {
    backgroundColor: '#e0e0e0',
  },
  cancelBtnText: {
    fontSize: 16,
    color: '#666',
  },
  confirmBtn: {
    backgroundColor: '#FC7D2E',
  },
  confirmBtnText: {
    fontSize: 16,
    color: '#fff',
  },
});
