import React, { useRef, useEffect } from 'react';
import { StyleSheet, ScrollView, Alert, TouchableOpacity, Animated, View } from 'react-native';
import { router } from 'expo-router';
import { LinearGradient } from 'expo-linear-gradient';

import { ThemedView } from '@/components/themed-view';
import { ThemedText } from '@/components/themed-text';
import { useAuth } from '@/hooks/use-auth';
import { useThemeColor } from '@/hooks/use-theme-color';
import { IconSymbol } from '@/components/ui/icon-symbol';

// 用户头像组件 - 优化版本
const UserAvatar = ({ image, name, size = 80 }: { image?: string; name: string; size?: number }) => {
  const placeholderColor = useThemeColor({}, 'imagePlaceholder');
  const textColor = useThemeColor({}, 'text');
  const animatedScale = useRef(new Animated.Value(1)).current;

  const getInitials = (name: string) => {
    return name
      .split(' ')
      .map(word => word[0])
      .join('')
      .toUpperCase()
      .slice(0, 2);
  };

  const handlePress = () => {
    Animated.sequence([
      Animated.timing(animatedScale, {
        toValue: 0.95,
        duration: 100,
        useNativeDriver: true,
      }),
      Animated.timing(animatedScale, {
        toValue: 1,
        duration: 100,
        useNativeDriver: true,
      }),
    ]).start();
  };

  return (
    <TouchableOpacity
      onPress={handlePress}
      activeOpacity={0.8}
      style={styles.avatarContainer}
    >
      <Animated.View
        style={[
          styles.avatar,
          {
            width: size,
            height: size,
            borderRadius: size / 2,
            backgroundColor: placeholderColor,
            transform: [{ scale: animatedScale }],
            shadowColor: '#000',
            shadowOffset: { width: 0, height: 4 },
            shadowOpacity: 0.15,
            shadowRadius: 12,
            elevation: 6,
          }
        ]}
      >
        {image ? (
          <ThemedText>图片</ThemedText>
        ) : (
          <ThemedText style={{
            fontSize: size / 2.5,
            fontWeight: '700',
            color: textColor,
          }}>
            {getInitials(name)}
          </ThemedText>
        )}
      </Animated.View>
    </TouchableOpacity>
  );
};

// 个人统计组件
const UserStats = () => {
  const cardColor = useThemeColor({}, 'card');

  return (
    <View style={styles.statsContainer}>
      <View style={[styles.statCard, { backgroundColor: cardColor }]}>
        <IconSymbol name="heart.fill" size={20} color="#ff6b6b" />
        <ThemedText style={styles.statNumber}>128</ThemedText>
        <ThemedText style={styles.statLabel}>创作作品</ThemedText>
      </View>
      <View style={[styles.statCard, { backgroundColor: cardColor }]}>
        <IconSymbol name="clock.fill" size={20} color="#4ECDC4" />
        <ThemedText style={styles.statNumber}>48</ThemedText>
        <ThemedText style={styles.statLabel}>使用时长(h)</ThemedText>
      </View>
      <View style={[styles.statCard, { backgroundColor: cardColor }]}>
        <IconSymbol name="star.fill" size={20} color="#FFD700" />
        <ThemedText style={styles.statNumber}>VIP</ThemedText>
        <ThemedText style={styles.statLabel}>会员等级</ThemedText>
      </View>
    </View>
  );
};

// 余额卡片组件 - 优化版本
const BalanceCard = () => {
  return (
    <View style={styles.balanceCardContainer}>
      <LinearGradient
        colors={['#4ECDC4', '#44A3A0', '#3D8B87']}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={styles.balanceCardGradient}
      >
        <View style={styles.balanceCardHeader}>
          <IconSymbol name="dollarsign.circle.fill" size={28} color="rgba(255,255,255,0.9)" />
          <ThemedText style={styles.balanceCardTitle}>账户余额</ThemedText>
        </View>

        <View style={styles.balanceAmountContainer}>
          <ThemedText style={styles.balanceCurrency}>¥</ThemedText>
          <ThemedText style={styles.balanceAmount}>0.00</ThemedText>
        </View>

        <TouchableOpacity
          style={styles.rechargeButton}
          onPress={() => router.push('/recharge')}
          activeOpacity={0.8}
        >
          <IconSymbol name="plus.circle.fill" size={18} color="rgba(255,255,255,0.9)" />
          <ThemedText style={styles.rechargeButtonText}>立即充值</ThemedText>
        </TouchableOpacity>

        <View style={styles.balanceCardFooter}>
          <IconSymbol name="info.circle" size={14} color="rgba(255,255,255,0.7)" />
          <ThemedText style={styles.balanceTipsText}>
            余额用于支付生成内容的消费
          </ThemedText>
        </View>
      </LinearGradient>
    </View>
  );
};

// 简单的设置列表组件
const SettingsList = () => {
  const tintColor = useThemeColor({}, 'tint');

  return (
    <ThemedView style={styles.sectionContent}>
      <ThemedView style={styles.sectionHeader}>
        <IconSymbol name="gearshape" size={24} color={tintColor} />
        <ThemedText style={styles.sectionTitle}>设置</ThemedText>
      </ThemedView>
      <TouchableOpacity
        style={styles.settingItem}
        onPress={() => router.push('/settings/account')}
      >
        <IconSymbol name="person.circle" size={20} color={tintColor} />
        <ThemedText style={styles.settingText}>账户设置</ThemedText>
        <IconSymbol name="chevron.right" size={16} color="#ccc" />
      </TouchableOpacity>
      <TouchableOpacity
        style={styles.settingItem}
        onPress={() => router.push('/settings/notification')}
      >
        <IconSymbol name="bell" size={20} color={tintColor} />
        <ThemedText style={styles.settingText}>通知设置</ThemedText>
        <IconSymbol name="chevron.right" size={16} color="#ccc" />
      </TouchableOpacity>
      <TouchableOpacity
        style={styles.settingItem}
        onPress={() => router.push('/settings/about')}
      >
        <IconSymbol name="info.circle" size={20} color={tintColor} />
        <ThemedText style={styles.settingText}>关于我们</ThemedText>
        <IconSymbol name="chevron.right" size={16} color="#ccc" />
      </TouchableOpacity>
    </ThemedView>
  );
};

export default function ProfileScreen() {
  const { user, session } = useAuth();
  const backgroundColor = useThemeColor({}, 'background');
  const cardColor = useThemeColor({}, 'card');
  const borderColor = useThemeColor({}, 'cardBorder');
  const headerAnim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(headerAnim, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: false,
    }).start();
  }, []);

  const handleLogout = () => {
    Alert.alert(
      '退出登录',
      '确定要退出登录吗？',
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          style: 'destructive',
          onPress: () => {
            // TODO: 实现登出逻辑
            router.replace('/(auth)/login');
          }
        }
      ]
    );
  };

  return (
    <View style={[styles.container, { backgroundColor }]}>
      {/* 渐变头部背景 */}
      <Animated.View
        style={[
          styles.headerBackground,
          {
            opacity: headerAnim,
          }
        ]}
      >
        <LinearGradient
          colors={['#ff6b6b', '#ff8e53', '#ff6b35']}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
          style={styles.headerGradient}
        />
      </Animated.View>

      <ScrollView
        style={styles.scrollView}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.scrollContent}
      >
        {/* 头部信息区域 */}
        <View style={styles.header}>
          <UserAvatar
            image={user?.image}
            name={user?.name || user?.username || '用户'}
            size={90}
          />
          <ThemedText style={styles.userName}>
            {user?.name || user?.username || '用户'}
          </ThemedText>
          <ThemedText style={styles.userEmail}>
            {user?.email || '未设置邮箱'}
          </ThemedText>
        </View>

        {/* 个人统计 */}
        <UserStats />

        {/* 余额卡片 */}
        <View style={[styles.section, styles.balanceSection]}>
          <BalanceCard />
        </View>

        {/* 生成记录 */}
        <ThemedView style={[styles.section, { backgroundColor: cardColor, borderColor }]}>
          <ThemedView style={styles.sectionContent}>
            <ThemedView style={styles.sectionHeader}>
              <IconSymbol name="clock.fill" size={24} color="#4ECDC4" />
              <ThemedText style={styles.sectionTitle}>生成记录</ThemedText>
            </ThemedView>
            <ThemedView style={styles.emptyContainer}>
              <IconSymbol name="doc.text.fill" size={48} color="#ccc" />
              <ThemedText style={styles.emptyText}>暂无生成记录</ThemedText>
              <ThemedText style={styles.emptySubText}>开始创建你的第一个作品吧</ThemedText>
            </ThemedView>
          </ThemedView>
        </ThemedView>

        {/* 设置列表 */}
        <ThemedView style={[styles.section, { backgroundColor: cardColor, borderColor }]}>
          <SettingsList />

          <TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
            <IconSymbol name="arrow.right.square" size={20} color="#FF3B30" />
            <ThemedText style={[styles.logoutText, { color: '#FF3B30' }]}>退出登录</ThemedText>
          </TouchableOpacity>
        </ThemedView>
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  headerBackground: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: 320,
    zIndex: -1,
  },
  headerGradient: {
    flex: 1,
    borderBottomLeftRadius: 40,
    borderBottomRightRadius: 40,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    paddingTop: 40,
    paddingBottom: 100,
  },
  header: {
    alignItems: 'center',
    paddingVertical: 40,
    paddingHorizontal: 20,
  },
  avatarContainer: {
    marginBottom: 4,
  },
  avatar: {
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 3,
    borderColor: 'rgba(255,255,255,0.3)',
    backgroundColor: 'rgba(255,255,255,0.1)',
  },
  userName: {
    fontSize: 24,
    fontWeight: '700',
    marginTop: 16,
    marginBottom: 4,
    color: '#fff',
    textShadowColor: 'rgba(0,0,0,0.2)',
    textShadowOffset: { width: 0, height: 1 },
    textShadowRadius: 4,
  },
  userEmail: {
    fontSize: 16,
    opacity: 0.8,
    color: 'rgba(255,255,255,0.9)',
  },
  statsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    marginBottom: 24,
    gap: 12,
  },
  statCard: {
    flex: 1,
    alignItems: 'center',
    paddingVertical: 20,
    paddingHorizontal: 12,
    borderRadius: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.08,
    shadowRadius: 24,
    elevation: 4,
  },
  statNumber: {
    fontSize: 20,
    fontWeight: '700',
    marginVertical: 8,
  },
  statLabel: {
    fontSize: 12,
    opacity: 0.7,
    textAlign: 'center',
  },
  section: {
    marginHorizontal: 16,
    marginBottom: 16,
    borderRadius: 16,
    borderWidth: 1,
    padding: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.08,
    shadowRadius: 24,
    elevation: 4,
  },
  balanceSection: {
    padding: 0,
    borderWidth: 0,
    backgroundColor: 'transparent',
    shadowColor: 'transparent',
    elevation: 0,
  },
  // 余额卡片样式
  balanceCardContainer: {
    marginHorizontal: 16,
    marginBottom: 24,
    borderRadius: 20,
    overflow: 'hidden',
    shadowColor: '#4ECDC4',
    shadowOffset: { width: 0, height: 8 },
    shadowOpacity: 0.3,
    shadowRadius: 16,
    elevation: 8,
  },
  balanceCardGradient: {
    padding: 24,
    alignItems: 'center',
  },
  balanceCardHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 20,
  },
  balanceCardTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: 'rgba(255,255,255,0.9)',
    marginLeft: 8,
  },
  balanceAmountContainer: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    justifyContent: 'center',
    marginBottom: 24,
  },
  balanceCurrency: {
    fontSize: 28,
    fontWeight: '600',
    color: 'rgba(255,255,255,0.8)',
    marginBottom: 4,
  },
  balanceAmount: {
    fontSize: 56,
    fontWeight: '800',
    color: '#fff',
    lineHeight: 56,
  },
  rechargeButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 14,
    paddingHorizontal: 32,
    backgroundColor: 'rgba(255,255,255,0.2)',
    borderRadius: 25,
    gap: 8,
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.3)',
    marginBottom: 20,
  },
  rechargeButtonText: {
    color: 'rgba(255,255,255,0.95)',
    fontSize: 16,
    fontWeight: '600',
  },
  balanceCardFooter: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    paddingTop: 16,
    borderTopWidth: 1,
    borderTopColor: 'rgba(255,255,255,0.2)',
  },
  balanceTipsText: {
    fontSize: 13,
    color: 'rgba(255,255,255,0.7)',
    flex: 1,
  },

  // 其他样式
  sectionContent: {
    flex: 1,
  },
  sectionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '700',
  },
  emptyContainer: {
    alignItems: 'center',
    paddingVertical: 60,
  },
  emptyText: {
    fontSize: 16,
    fontWeight: '600',
    marginTop: 16,
    marginBottom: 8,
  },
  emptySubText: {
    fontSize: 14,
    color: '#666',
  },
  settingItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 18,
    borderBottomWidth: 1,
    borderBottomColor: '#f5f5f5',
    gap: 16,
  },
  settingText: {
    fontSize: 16,
    flex: 1,
    fontWeight: '500',
  },
  logoutButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 18,
    paddingHorizontal: 16,
    gap: 16,
    marginTop: 8,
    borderTopWidth: 1,
    borderTopColor: '#f5f5f5',
  },
  logoutText: {
    fontSize: 16,
    fontWeight: '600',
  },
});