/**
 * 分类占比图（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/chartStats';
import type { Transaction } from '../../domain/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, fontWeight: '600' }]}
              numberOfLines={1}
            >
              {d.category.replace('Expenses:', '').replace('Income:', '')}
            </Text>
            <View style={[styles.barWrap, { backgroundColor: theme.colors.bgTertiary, borderColor: theme.colors.border, borderWidth: StyleSheet.hairlineWidth }]}>
              <View style={[styles.bar, { width: `${(d.amount / maxAmount) * 100}%`, backgroundColor: theme.colors.accent }]} />
            </View>
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, width: 55, textAlign: 'right', fontVariant: ['tabular-nums'], fontSize: 13 }]}>
              {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: { width: 120, height: 8, borderRadius: 4, overflow: 'hidden' },
  bar: { height: '100%', borderRadius: 4 },
});
