import React, { useMemo } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { calculateAccountTotalBalance, type AccountNode } from '../../domain/taxonomy/accountTree';

interface AccountTreeProps {
  nodes: AccountNode[];
  /** 最大展示深度（默认全部）。 */
  maxDepth?: number;
}

/** 账户树展示（主题化，缩进显示层级 + 余额）。 */
export function AccountTree({ nodes, maxDepth = Infinity }: AccountTreeProps) {
  return (
    <View style={{ gap: 4 }}>
      {nodes.map(node => (
        <AccountTreeNode key={node.fullName} node={node} depth={0} maxDepth={maxDepth} />
      ))}
    </View>
  );
}

const AccountTreeNode = React.memo(function AccountTreeNode({ node, depth, maxDepth }: { node: AccountNode; depth: number; maxDepth: number }) {
  const { theme } = useTheme();
  const t = useT();
  const total = useMemo(() => calculateAccountTotalBalance(node), [node]);
  const isLeaf = node.children.length === 0;

  let displayName = node.name;
  if (depth === 0) {
    const localized = t(`account.rootTypes.${node.name as 'Assets' | 'Liabilities' | 'Income' | 'Expenses' | 'Equity'}`);
    if (localized && !localized.startsWith('account.')) {
      displayName = localized;
    }
  }

  return (
    <View>
      <View style={[styles.row, { paddingLeft: depth * 16 }]}>
        <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary, fontWeight: depth === 0 ? '700' : '400' }]}>
          {isLeaf ? '• ' : ''}{displayName}
        </Text>
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
          {total}
        </Text>
      </View>
      {depth < maxDepth && node.children.map(child => (
        <AccountTreeNode key={child.fullName} node={child} depth={depth + 1} maxDepth={maxDepth} />
      ))}
    </View>
  );
});

const styles = StyleSheet.create({
  row: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingVertical: 4 },
});
