/**
 * 年度报告图表（plan.md「5.2 年度报告」；P4：去内嵌月报，加月度节奏迷你图）。
 * 展示年度收支/分类/月度节奏。
 */
import React, { useMemo } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { generateAnnualReport } from '../../domain/stats/annualReport';
import type { Transaction } from '../../domain/core/types';

export function AnnualReport({ transactions, year }: { transactions: Transaction[]; year: number }) {
  const { theme } = useTheme();
  const t = useT();
  const report = useMemo(() => generateAnnualReport(transactions, year), [transactions, year]);
  // 展示层比率计算，允许 parseFloat（非记账金额）
  const maxExpense = useMemo(
    () => Math.max(...report.monthlyTrend.map(m => parseFloat(m.expense) || 0)),
    [report],
  );

  return (
    <View style={styles.container}>
      <View style={[styles.card, { backgroundColor: theme.colors.bgSecondary, borderRadius: theme.radii.lg, padding: theme.spacing.md }]}>
        <Text style={[theme.typography.h2, { color: theme.colors.fgPrimary }]}>{t('report.annualTitle', { year })}</Text>
        <View style={styles.statsRow}>
          <View style={styles.statItem}>
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('report.annualIncome')}</Text>
            <Text style={[theme.typography.h3, { color: theme.colors.financial.income }]}>{report.totalIncome}</Text>
          </View>
          <View style={styles.statItem}>
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('report.annualExpense')}</Text>
            <Text style={[theme.typography.h3, { color: theme.colors.financial.expense }]}>{report.totalExpense}</Text>
          </View>
          <View style={styles.statItem}>
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('report.annualNet')}</Text>
            <Text style={[theme.typography.h3, { color: theme.colors.accent }]}>{report.netIncome}</Text>
          </View>
        </View>
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
          {t('report.annualStats', { count: report.transactionCount, avg: report.averageDailyExpense })}
        </Text>
      </View>

      {report.topCategories.length > 0 && (
        <View style={[styles.card, { backgroundColor: theme.colors.bgSecondary, borderRadius: theme.radii.lg, padding: theme.spacing.md }]}>
          <Text style={[theme.typography.h3, { color: theme.colors.fgPrimary }]}>{t('report.topCategory')}</Text>
          {report.topCategories.slice(0, 5).map(c => (
            <View key={c.category} style={[styles.catRow, { borderTopColor: theme.colors.progressBg }]}>
              <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary, flex: 1 }]}>{c.category.replace('Expenses:', '')}</Text>
              <Text style={[theme.typography.bodySmall, { color: theme.colors.fgSecondary }]}>{c.amount} ({c.percentage}%)</Text>
            </View>
          ))}
        </View>
      )}

      <View style={[styles.card, { backgroundColor: theme.colors.bgSecondary, borderRadius: theme.radii.lg, padding: theme.spacing.md }]}>
        <Text style={[theme.typography.h3, { color: theme.colors.fgPrimary }]}>{t('report.monthlyRhythm')}</Text>
        <View style={styles.rhythmRow}>
          {report.monthlyTrend.map(m => {
            const ratio = maxExpense > 0 ? Math.min(parseFloat(m.expense) / maxExpense, 1) : 0;
            return (
              <View key={m.month} style={styles.rhythmCol}>
                {/* 节奏条圆角使用 theme.radii.sm / 2，避免硬编码 */}
                <View style={[styles.rhythmTrack, { backgroundColor: theme.colors.bgTertiary, borderRadius: theme.radii.sm / 2 }]}>
                  <View style={[styles.rhythmFill, { height: `${Math.max(ratio * 100, 2)}%`, backgroundColor: theme.colors.financial.expense, borderRadius: theme.radii.sm / 2 }]} />
                </View>
                <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, fontSize: theme.typography.caption.fontSize - 3 }]}>{Number(m.month.slice(5))}</Text>
              </View>
            );
          })}
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { gap: 12 },
  card: { gap: 8 },
  statsRow: { flexDirection: 'row', justifyContent: 'space-around' },
  statItem: { alignItems: 'center', gap: 4 },
  catRow: { flexDirection: 'row', borderTopWidth: 1, paddingTop: 8 },
  rhythmRow: { flexDirection: 'row', gap: 4, height: 64, marginTop: 8 },
  rhythmCol: { flex: 1, alignItems: 'center', gap: 4 },
  rhythmTrack: { flex: 1, width: '100%', justifyContent: 'flex-end', overflow: 'hidden' },
  rhythmFill: { width: '100%' },
});