import { View, Text, StyleSheet, FlatList, ActivityIndicator, RefreshControl, useColorScheme } from 'react-native';
import { useNavigation, useFocusEffect } from 'expo-router';
import React, { useEffect, useState, useCallback } from 'react';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import { Ionicons } from '@expo/vector-icons';
import Animated, { FadeInDown, FadeIn } from 'react-native-reanimated';
import { LinearGradient } from 'expo-linear-gradient';
import AnimatedButton from '@/components/common/AnimatedButton';
import GlassCard from '@/components/common/GlassCard';

export default function WalletScreen() {
  const navigation = useNavigation();
  const colorScheme = useColorScheme() ?? 'light';
  const isDark = colorScheme === 'dark';
  const theme = Colors[colorScheme as 'light' | 'dark'];

  const [history, setHistory] = useState<any[]>([]);
  const [balance, setBalance] = useState('0.00');
  const [currency, setCurrency] = useState('');
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const fetchWalletData = async () => {
    try {
      const response = await api.post('/walletHistory');
      const data = response.data;
      // API returns: { data: [...], totalAmountBalance: "X", Currency: "€" }
      setHistory(data.data || []);
      setBalance(data.totalAmountBalance || '0.00');
      setCurrency('');
    } catch (error) {
      console.error('Error fetching wallet data:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(
    useCallback(() => {
      navigation.getParent()?.setOptions({ headerTitle: 'Carteira' });
      fetchWalletData();
    }, [navigation])
  );

  const onRefresh = () => {
    setRefreshing(true);
    fetchWalletData();
  };

  const renderTransaction = ({ item, index }: { item: any; index: number }) => (
    <Animated.View entering={FadeInDown.duration(400).delay(index * 100)}>
      <GlassCard intensity={8} style={styles.transactionItem}>
        <View style={styles.transRow}>
          <View style={[styles.iconContainer, { backgroundColor: item.type === 'debit' ? `${theme.error}15` : `${theme.success}15` }]}>
            <Ionicons 
              name={item.type === 'debit' ? 'arrow-up' : 'arrow-down'} 
              size={18} 
              color={item.type === 'debit' ? theme.error : theme.success} 
            />
          </View>
          <View style={styles.transactionInfo}>
            <Text style={[styles.transactionTitle, { color: theme.text }]}>{item.remark || 'Transação'}</Text>
            <Text style={[styles.transactionDate, { color: theme.textMuted }]}>{new Date(item.created_at).toLocaleDateString()}</Text>
          </View>
          <Text style={[styles.transactionAmount, { color: item.type === 'debit' ? theme.error : theme.success }]}>
            {item.type === 'debit' ? '-' : '+'}{item.currencySymbol || currency}{item.amount}
          </Text>
        </View>
      </GlassCard>
    </Animated.View>
  );

  if (loading && !refreshing) {
    return (
      <View style={[styles.loaderContainer, { backgroundColor: theme.background }]}>
        <ActivityIndicator size="large" color={theme.primary} />
      </View>
    );
  }

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      <FlatList
        data={history}
        keyExtractor={(item) => item.id.toString()}
        renderItem={renderTransaction}
        contentContainerStyle={styles.listContent}
        showsVerticalScrollIndicator={false}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.primary} />}
        ListHeaderComponent={
          <>
            <Animated.View entering={FadeInDown.duration(500).delay(100)}>
              <LinearGradient
                colors={theme.gradients.primary as [string, string]}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
                style={styles.balanceCard}
              >
                <View style={styles.cardTopRow}>
                  <Text style={styles.balanceLabel}>Saldo Atual</Text>
                  <Ionicons name="card" size={24} color="rgba(255,255,255,0.7)" />
                </View>
                <Text style={styles.balanceValue}>{currency}{balance}</Text>
                
                <View style={styles.cardNumber}>
                  <Text style={styles.cardDots}>••••  ••••  ••••</Text>
                  <Text style={styles.cardEnd}>1234</Text>
                </View>
              </LinearGradient>
            </Animated.View>

            <Animated.View entering={FadeIn.duration(400).delay(300)} style={styles.actionsRow}>
              <AnimatedButton 
                title="Adicionar Fundos" 
                onPress={() => {}} 
                style={{ flex: 1 }} 
              />
            </Animated.View>

            <Animated.View entering={FadeIn.duration(400).delay(400)}>
              <Text style={[styles.sectionTitle, { color: theme.text }]}>Histórico de Transações</Text>
            </Animated.View>
          </>
        }
        ListEmptyComponent={
          <Animated.View entering={FadeIn.duration(500)} style={styles.emptyContainer}>
            <Ionicons name="receipt-outline" size={48} color={theme.border} style={{ marginBottom: 12 }} />
            <Text style={[styles.emptyText, { color: theme.textMuted }]}>Sem transações recentes.</Text>
          </Animated.View>
        }
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  loaderContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  listContent: { paddingHorizontal: 20, paddingBottom: 100 },
  balanceCard: { 
    marginTop: 10,
    padding: 24, 
    borderRadius: 24,
    shadowColor: '#4A3AFF',
    shadowOffset: { width: 0, height: 10 },
    shadowOpacity: 0.3,
    shadowRadius: 20,
    elevation: 8,
    minHeight: 180,
    justifyContent: 'space-between',
  },
  cardTopRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  balanceLabel: { color: 'rgba(255,255,255,0.8)', fontSize: 15, fontWeight: '500' },
  balanceValue: { color: '#fff', fontSize: 40, fontWeight: '800', letterSpacing: -1, marginTop: 8 },
  cardNumber: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 20,
  },
  cardDots: { color: 'rgba(255,255,255,0.6)', fontSize: 18, letterSpacing: 2 },
  cardEnd: { color: '#fff', fontSize: 16, fontWeight: '600', marginLeft: 10 },
  actionsRow: {
    flexDirection: 'row',
    marginTop: 20,
    marginBottom: 20,
  },
  sectionTitle: { fontSize: 18, fontWeight: '700', letterSpacing: -0.5, marginBottom: 15 },
  transactionItem: { 
    marginBottom: 12, 
    borderRadius: 16,
    padding: 14,
  },
  transRow: {
    flexDirection: 'row', 
    alignItems: 'center', 
  },
  iconContainer: { width: 44, height: 44, borderRadius: 22, justifyContent: 'center', alignItems: 'center' },
  transactionInfo: { flex: 1, marginLeft: 14 },
  transactionTitle: { fontSize: 15, fontWeight: '600', letterSpacing: -0.3 },
  transactionDate: { fontSize: 13, marginTop: 4, fontWeight: '500' },
  transactionAmount: { fontSize: 16, fontWeight: '800' },
  emptyContainer: { padding: 40, alignItems: 'center', justifyContent: 'center' },
  emptyText: { fontSize: 15 }
});
