import React, { useEffect, useState } from 'react';
import {
  View, Text, StyleSheet, FlatList, ActivityIndicator,
  RefreshControl, useColorScheme, TouchableOpacity
} from 'react-native';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import Animated, { FadeInDown } from 'react-native-reanimated';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { UnifiedBottomNav } from '@/components/home/UnifiedBottomNav';

const TRANSACTION_ICON: keyof typeof Ionicons.glyphMap = 'receipt-outline';

const getStatusColors = (status: string, theme: any) => {
  const s = status?.toLowerCase() || '';
  if (s === 'paid') return { bg: `${theme.success}20`, text: theme.success, label: 'Pago' };
  if (s === 'unpaid') return { bg: `${theme.warning}20`, text: theme.warning, label: 'Pendente' };
  if (s === 'refund') return { bg: `${theme.error}20`, text: theme.error, label: 'Reembolsado' };
  return { bg: theme.secondary, text: theme.textMuted, label: status || '—' };
};

const translatePaymentMethod = (method: string) => {
  const m = method?.toLowerCase() || '';
  if (m === 'wallet') return 'Carteira';
  if (m === 'cod') return 'Pagamento no Local';
  if (m === 'stripe') return 'Cartão de Crédito';
  return method || '—';
};

export default function TransactionsScreen() {
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];
  const router = useRouter();

  const [transactions, setTransactions] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const fetchTransactions = async () => {
    try {
      const response = await api.post('/transactionlistapi');
      setTransactions(response.data?.data?.transactions || []);
    } catch (error) {
      console.error('Error fetching transactions:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => { fetchTransactions(); }, []);
  const onRefresh = () => { setRefreshing(true); fetchTransactions(); };

  const renderItem = ({ item, index }: { item: any; index: number }) => {
    const statusColors = getStatusColors(item.payment?.status, theme);
    const payIcon = TRANSACTION_ICON;

    return (
      <Animated.View entering={FadeInDown.duration(350).delay(index * 70)}>
        <TouchableOpacity
          activeOpacity={0.85}
          onPress={() => router.push({ pathname: '/(drawer)/transaction/[id]' as any, params: { id: item.id, data: JSON.stringify(item) } })}
        >
          <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.primary }]}>
            {/* Accent bar */}
            <View style={[styles.accentBar, { backgroundColor: theme.primary }]} />

            <View style={styles.cardBody}>
              {/* Header: Service + Amount */}
              <View style={styles.headerRow}>
                <View style={[styles.iconWrap, { backgroundColor: `${theme.primary}15` }]}>
                  <Ionicons name={payIcon} size={20} color={theme.primary} />
                </View>
                <View style={styles.headerText}>
                  <Text style={[styles.serviceName, { color: theme.text }]} numberOfLines={1}>
                    {item.service?.name || 'Transação'}
                  </Text>
                </View>
                <View style={[styles.badge, { backgroundColor: statusColors.bg }]}>
                  <Text style={[styles.badgeText, { color: statusColors.text }]}>
                    {statusColors.label}
                  </Text>
                </View>
              </View>

              {/* Financial breakdown */}
              <View style={[styles.financeRow, { borderColor: `${theme.border}60` }]}>
                <View style={styles.finCell}>
                  <Text style={[styles.finLabel, { color: theme.textMuted }]}>Valor</Text>
                  <Text style={[styles.finValue, { color: theme.primary }]}>
                    {item.amount?.service_amount || '0.00'}
                  </Text>
                </View>
                <View style={[styles.finDivider, { backgroundColor: theme.border }]} />
                <View style={styles.finCell}>
                  <Text style={[styles.finLabel, { color: theme.textMuted }]}>IVA</Text>
                  <Text style={[styles.finValue, { color: theme.text }]}>
                    {item.amount?.tax || '0.00'}
                  </Text>
                </View>
                <View style={[styles.finDivider, { backgroundColor: theme.border }]} />
                <View style={styles.finCell}>
                  <Text style={[styles.finLabel, { color: theme.textMuted }]}>Total</Text>
                  <Text style={[styles.finValue, styles.totalValue, { color: theme.text }]}>
                    {item.amount?.total_amount || '0.00'}
                  </Text>
                </View>
              </View>

              {/* Footer: date + payment type + view details */}
              <View style={styles.footerRow}>
                <View style={styles.footerMeta}>
                  <Ionicons name="calendar-outline" size={12} color={theme.textMuted} />
                  <Text style={[styles.metaText, { color: theme.textMuted }]}>{item.date || '—'}</Text>
                </View>
                <View style={styles.footerMeta}>
                  <Ionicons name={payIcon} size={12} color={theme.textMuted} />
                  <Text style={[styles.metaText, { color: theme.textMuted }]}>
                    {translatePaymentMethod(item.payment?.type)}
                  </Text>
                </View>
                <View style={styles.viewBtn}>
                  <Text style={[styles.viewBtnText, { color: theme.primary }]}>Ver Detalhes</Text>
                  <Ionicons name="chevron-forward" size={12} color={theme.primary} />
                </View>
              </View>
            </View>
          </View>
        </TouchableOpacity>
      </Animated.View>
    );
  };

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

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      <FlatList
        data={transactions}
        keyExtractor={(item) => item.id?.toString()}
        renderItem={renderItem}
        contentContainerStyle={styles.list}
        showsVerticalScrollIndicator={false}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.primary} />}
        ListEmptyComponent={
          <View style={styles.emptyContainer}>
            <Ionicons name="receipt-outline" size={56} color={theme.border} />
            <Text style={[styles.emptyTitle, { color: theme.text }]}>Sem Transações</Text>
            <Text style={[styles.emptySubtitle, { color: theme.textMuted }]}>
              O seu histórico de pagamentos vai aparecer aqui.
            </Text>
          </View>
        }
      />
      <UnifiedBottomNav />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  center: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  list: { padding: 16, paddingBottom: 100 },
  card: {
    flexDirection: 'row',
    borderRadius: 14,
    borderWidth: StyleSheet.hairlineWidth,
    marginBottom: 12,
    overflow: 'hidden',
  },
  accentBar: { width: 4 },
  cardBody: { flex: 1, padding: 14 },
  headerRow: { flexDirection: 'row', alignItems: 'center', marginBottom: 12 },
  iconWrap: {
    width: 38, height: 38, borderRadius: 10,
    justifyContent: 'center', alignItems: 'center', marginRight: 10,
  },
  headerText: { flex: 1 },
  serviceName: { fontSize: 15, fontWeight: '700', letterSpacing: -0.2 },
  providerName: { fontSize: 12, marginTop: 2 },
  badge: { paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6 },
  badgeText: { fontSize: 10, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5 },
  financeRow: {
    flexDirection: 'row',
    borderWidth: StyleSheet.hairlineWidth,
    borderRadius: 10,
    marginBottom: 12,
    overflow: 'hidden',
  },
  finCell: { flex: 1, alignItems: 'center', paddingVertical: 10 },
  finDivider: { width: StyleSheet.hairlineWidth },
  finLabel: { fontSize: 11, fontWeight: '500', marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.3 },
  finValue: { fontSize: 14, fontWeight: '700' },
  totalValue: { fontWeight: '800' },
  footerRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  footerMeta: { flexDirection: 'row', alignItems: 'center', gap: 4 },
  metaText: { fontSize: 11, fontWeight: '500' },
  viewBtn: { flexDirection: 'row', alignItems: 'center', gap: 2 },
  viewBtnText: { fontSize: 12, fontWeight: '700' },
  emptyContainer: { alignItems: 'center', justifyContent: 'center', paddingTop: 100, gap: 12 },
  emptyTitle: { fontSize: 18, fontWeight: '700' },
  emptySubtitle: { fontSize: 14, textAlign: 'center', paddingHorizontal: 40 },
});
