import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { useTheme } from '../theme';
import { useT } from '../i18n';
import { CategoryIcon } from './CategoryIcon';
import { Touchable } from './Touchable';
import type { Transaction } from '../domain/types';

interface TransactionCardProps {
  transaction: Transaction;
  onPress?: (t: Transaction) => void;
  /** 命中分类 id（调用方按 linkedAccount 匹配）；缺省用方向兜底图标。 */
  categoryId?: string;
  /** 时间线分组下隐藏日期（默认 true 保持旧行为）。 */
  showDate?: boolean;
}

/** 交易卡片：CategoryIcon 圆底 + 摘要/账户小字 + 右侧等宽金额（支出黑、收入绿+、转账蓝）。 */
export const TransactionCard = React.memo(function TransactionCard({ transaction, onPress, categoryId, showDate = true }: TransactionCardProps) {
  const { theme } = useTheme();
  const t = useT();
  const isExpense = transaction.postings.some(p => p.account.startsWith('Expenses'));
  const isIncome = transaction.postings.some(p => p.account.startsWith('Income'));
  const direction = isExpense ? 'expense' : isIncome ? 'income' : 'transfer';
  const rawAmount = transaction.postings.find(p => p.amount)?.amount ?? '';
  const absAmount = rawAmount.replace(/^-/, '');
  const amountColor = direction === 'income' ? theme.colors.financial.income
    : direction === 'transfer' ? theme.colors.financial.transfer
    : theme.colors.fgPrimary;
  const amountText = direction === 'income' ? `+${absAmount}` : direction === 'expense' ? `-${absAmount}` : absAmount;
  // 账户小字：第一条资金腿的短名
  const assetAccount = transaction.postings.find(p => p.account.startsWith('Assets') || p.account.startsWith('Liabilities'))?.account;
  const accountShort = assetAccount?.split(':').pop();
  const subtitle = [
    showDate ? transaction.date.slice(0, 10) : '',
    accountShort ?? '',
  ].filter(Boolean).join(' · ');

  return (
    <Touchable
      accessibilityRole="button"
      accessibilityLabel={`${transaction.narration || transaction.payee || ''} ${amountText} ${transaction.date.slice(0, 10)}`}
      onPress={() => onPress?.(transaction)}
      style={[
        styles.card,
        {
          backgroundColor: theme.colors.bgSecondary,
          borderRadius: theme.radii.lg,
          padding: theme.spacing.md,
          borderWidth: StyleSheet.hairlineWidth,
          borderColor: theme.colors.border,
        },
      ]}
    >
      <CategoryIcon categoryId={categoryId ?? direction} size={36} />
      <View style={styles.body}>
        <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, fontWeight: '600' }]} numberOfLines={1}>
          {transaction.narration || transaction.payee || t('transaction.noSummary')}
        </Text>
        {subtitle ? (
          <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginTop: 2 }]} numberOfLines={1}>
            {subtitle}
          </Text>
        ) : null}
      </View>
      <Text style={[theme.typography.body, { color: amountColor, fontWeight: '700', fontSize: 15, fontVariant: ['tabular-nums'] }]}>
        {amountText}
      </Text>
      {transaction.tags.length > 0 && (
        <View style={styles.tags}>
          {transaction.tags.map(tag => (
            <Text key={tag} style={[styles.tag, { backgroundColor: theme.colors.accentLight, color: theme.colors.accent, fontWeight: '600' }]}>
              #{tag}
            </Text>
          ))}
        </View>
      )}
    </Touchable>
  );
});

const styles = StyleSheet.create({
  card: { marginBottom: 8, flexDirection: 'row', alignItems: 'center', gap: 10, flexWrap: 'wrap' },
  body: { flex: 1 },
  tags: { flexDirection: 'row', gap: 4, marginLeft: 46, flexBasis: '100%', flexWrap: 'wrap' },
  tag: { fontSize: 11, paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, overflow: 'hidden' },
});
