/**
 * 净资产趋势图（plan.md「5.2 净资产趋势」）。
 */
import React, { useEffect, useMemo, useRef } from 'react';
import { Animated, StyleSheet, Text, View } from 'react-native';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { calculateNetWorthTrend } from '../../domain/stats/netWorth';
import type { Transaction } from '../../domain/core/types';

export function NetWorthChart({ transactions, dates }: { transactions: Transaction[]; dates: string[] }) {
  const { theme } = useTheme();
  const t = useT();
  const points = useMemo(() => calculateNetWorthTrend(transactions, dates), [transactions, dates]);
  const maxAbs = Math.max(...points.map(p => Math.abs(parseFloat(p.netWorth))), 1);
  const progress = useRef(new Animated.Value(0)).current;
  useEffect(() => {
    Animated.timing(progress, { toValue: 1, duration: 600, useNativeDriver: false }).start();
  }, [progress]);

  return (
    <View style={[styles.container, { backgroundColor: theme.colors.bgSecondary, borderRadius: theme.radii.lg, padding: theme.spacing.md }]}>
      <Text style={[theme.typography.h3, { color: theme.colors.fgPrimary }]}>{t('report.netWorthTitle')}</Text>
      <View style={styles.chart}>
        {points.map(p => (
          <View key={p.date} style={styles.col}>
            <View style={styles.barWrap}>
              {/* 柱状条圆角使用 theme.radii.sm / 2，避免硬编码 */}
              <Animated.View style={[styles.bar, {
                height: progress.interpolate({ inputRange: [0, 1], outputRange: [0, (Math.abs(parseFloat(p.netWorth)) / maxAbs) * 100] }),
                backgroundColor: parseFloat(p.netWorth) >= 0 ? theme.colors.accent : theme.colors.error,
                borderRadius: theme.radii.sm / 2,
              }]} />
            </View>
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, fontSize: theme.typography.caption.fontSize - 3 }]}>{p.date.slice(5)}</Text>
          </View>
        ))}
      </View>
      {points.length > 0 && (
        <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary }]}>
          {t('report.netWorthCurrent', { amount: points[points.length - 1].netWorth })}
        </Text>
      )}
      {points.length === 0 && <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('common.noData')}</Text>}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { gap: 8 },
  chart: { flexDirection: 'row', alignItems: 'flex-end', height: 120, gap: 4 },
  col: { flex: 1, alignItems: 'center', gap: 4 },
  barWrap: { height: 100, justifyContent: 'flex-end', width: '100%', alignItems: 'center' },
  bar: { width: 12 },
});