/**
 * 分类占比图（plan.md「5.2 图表与可视化」）。
 * 采用卡片化布局与磨砂感水平胶囊进度条。
 */
import React, { useMemo } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { groupByCategory } from '../../domain/stats/chartStats';
import type { Transaction } from '../../domain/core/types';

export function CategoryPie({ transactions }: { transactions: Transaction[] }) {
  const { theme } = useTheme();
  const t = useT();
  const data = useMemo(() => groupByCategory(transactions), [transactions]);
  const maxAmount = Math.max(...data.map(d => d.amount), 1);

  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.categoryTitle')}
      </Text>
      <View style={styles.list}>
        {data.map(d => (
          <View key={d.category} style={styles.row}>
            <Text
              style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary, flex: 1, maxWidth: '38%', fontWeight: '600' }]}
              numberOfLines={1}
            >
              {d.category.replace('Expenses:', '').replace('Income:', '')}
            </Text>
            {/* 进度条圆角使用 theme.radii.sm / 2，避免硬编码 */}
            <View style={[styles.barWrap, { backgroundColor: theme.colors.bgTertiary, borderColor: theme.colors.border, borderWidth: StyleSheet.hairlineWidth, borderRadius: theme.radii.sm / 2 }]}>
              <View style={[styles.bar, { width: `${(d.amount / maxAmount) * 100}%`, backgroundColor: theme.colors.accent, borderRadius: theme.radii.sm / 2 }]} />
            </View>
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, width: 55, textAlign: 'right', fontVariant: ['tabular-nums'], fontSize: theme.typography.bodySmall.fontSize - 1 }]}>
              {d.percentage}%
            </Text>
          </View>
        ))}
      </View>
      {data.length === 0 && (
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, textAlign: 'center', marginVertical: 15 }]}>
          {t('common.noData')}
        </Text>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { gap: 10 },
  list: { gap: 8 },
  row: { flexDirection: 'row', alignItems: 'center', gap: 10 },
  barWrap: { flex: 1, height: 8, overflow: 'hidden' },
  bar: { height: '100%' },
});