import React from 'react';
import { View, Text, StyleSheet, ScrollView, useColorScheme } from 'react-native';
import { useLocalSearchParams } from 'expo-router';
import { Colors } from '@/constants/theme';
import GlassCard from '@/components/common/GlassCard';
import Animated, { FadeInDown } from 'react-native-reanimated';
import { Ionicons } from '@expo/vector-icons';

const Row = ({ label, value, valueColor, theme }: { label: string; value: string; valueColor?: string; theme: any }) => (
  <View style={styles.row}>
    <Text style={[styles.rowLabel, { color: theme.textMuted }]}>{label}</Text>
    <Text style={[styles.rowValue, { color: valueColor || theme.text }]} numberOfLines={2}>{value || '—'}</Text>
  </View>
);

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 TransactionDetailScreen() {
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];
  const { data } = useLocalSearchParams<{ id: string; data: string }>();

  let item: any = null;
  try {
    item = data ? JSON.parse(data) : null;
  } catch {
    item = null;
  }

  if (!item) {
    return (
      <View style={[styles.center, { backgroundColor: theme.background }]}>
        <Ionicons name="alert-circle-outline" size={48} color={theme.textMuted} />
        <Text style={[styles.errorText, { color: theme.textMuted }]}>Transação não encontrada.</Text>
      </View>
    );
  }

  const statusColors = getStatusColors(item.payment?.status, theme);

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      <ScrollView contentContainerStyle={styles.scroll} showsVerticalScrollIndicator={false}>

        {/* Hero card: Amount */}
        <Animated.View entering={FadeInDown.duration(400).delay(50)}>
          <View style={[styles.heroCard, { backgroundColor: theme.primary }]}>
            <Text style={styles.heroLabel}>Valor Total</Text>
            <Text style={styles.heroAmount}>
              {item.amount?.total_amount || '0.00'}
            </Text>
            <View style={[styles.heroBadge, { backgroundColor: statusColors.bg }]}>
              <Text style={[styles.heroBadgeText, { color: statusColors.text }]}>
                {statusColors.label}
              </Text>
            </View>
            <Text style={styles.heroOrderId}>Ref: #{item.order_id || item.id}</Text>
          </View>
        </Animated.View>

        {/* Financial breakdown */}
        <Animated.View entering={FadeInDown.duration(400).delay(100)}>
          <GlassCard style={styles.card}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>💰 Resumo Financeiro</Text>
            <Row theme={theme} label="Valor do Serviço" value={`${item.amount?.service_amount || '0.00'}`} valueColor={theme.primary} />
            <Row theme={theme} label="IVA / Imposto" value={`${item.amount?.tax || '0.00'}`} />
            <Row theme={theme} label="Total Pago" value={`${item.amount?.total_amount || '0.00'}`} valueColor={theme.text} />
          </GlassCard>
        </Animated.View>

        {/* Payment info */}
        <Animated.View entering={FadeInDown.duration(400).delay(150)}>
          <GlassCard style={styles.card}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>💳 Pagamento</Text>
            <Row theme={theme} label="Método de Pagamento" value={translatePaymentMethod(item.payment?.type)} />
            <Row theme={theme} label="Estado" value={statusColors.label} />
            {item.payment?.transaction_id && item.payment.transaction_id !== 'null' && (
              <Row theme={theme} label="ID da Transação" value={item.payment.transaction_id} />
            )}
            <Row theme={theme} label="Data" value={item.date || '—'} />
          </GlassCard>
        </Animated.View>

        {/* Customer info */}
        <Animated.View entering={FadeInDown.duration(400).delay(250)}>
          <GlassCard style={styles.card}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>👤 Cliente</Text>
            <Row theme={theme} label="Nome" value={item.customer?.name || '—'} />
            <Row theme={theme} label="Email" value={item.customer?.email || '—'} />
          </GlassCard>
        </Animated.View>

        {/* Additional services if any */}
        {item.additional_services?.length > 0 && (
          <Animated.View entering={FadeInDown.duration(400).delay(300)}>
            <GlassCard style={styles.card}>
              <Text style={[styles.sectionTitle, { color: theme.text }]}>➕ Serviços Adicionais</Text>
              {item.additional_services.map((s: any, i: number) => (
                <Row key={i} theme={theme} label={s.name || `Serviço ${i + 1}`} value={`${s.price || '0.00'}`} />
              ))}
            </GlassCard>
          </Animated.View>
        )}

        <View style={{ height: 40 }} />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  center: { flex: 1, justifyContent: 'center', alignItems: 'center', gap: 12 },
  scroll: { padding: 16 },
  heroCard: {
    borderRadius: 18,
    padding: 24,
    alignItems: 'center',
    marginBottom: 16,
  },
  heroLabel: { color: 'rgba(255,255,255,0.7)', fontSize: 13, fontWeight: '600', marginBottom: 6 },
  heroAmount: { color: '#FFF', fontSize: 36, fontWeight: '900', letterSpacing: -1, marginBottom: 12 },
  heroBadge: {
    paddingHorizontal: 14, paddingVertical: 6, borderRadius: 20, marginBottom: 10,
  },
  heroBadgeText: { fontSize: 12, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5 },
  heroOrderId: { color: 'rgba(255,255,255,0.6)', fontSize: 12 },
  card: { marginBottom: 12 },
  sectionTitle: { fontSize: 15, fontWeight: '800', marginBottom: 14, letterSpacing: -0.3 },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    paddingVertical: 9,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: 'rgba(150,150,150,0.15)',
  },
  rowLabel: { fontSize: 13, fontWeight: '500', flex: 1 },
  rowValue: { fontSize: 13, fontWeight: '700', flex: 1, textAlign: 'right', marginLeft: 10 },
  errorText: { fontSize: 16 },
});
