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

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

/** 交易卡片：CategoryIcon 圆底 + 摘要/账户小字 + 右侧等宽金额（支出黑、收入绿+、转账蓝）。 */
/** 图标尺寸与图标-正文间距：tags 行左缩进由此推导，避免魔法数字。 */
const ICON_SIZE = 36;
const ICON_GAP = 10;

// 搜索关键词高亮：大小写不敏感，命中片段用语义色加粗
function highlightText(text: string, keyword: string | undefined, highlightColor: string): React.ReactNode {
  const kw = keyword?.trim().toLowerCase();
  if (!kw) return text;
  const lower = text.toLowerCase();
  if (!lower.includes(kw)) return text;
  const hitStyle = { color: highlightColor, fontWeight: '700' as const };
  const parts: React.ReactNode[] = [];
  let cursor = 0;
  let pos = lower.indexOf(kw);
  let key = 0;
  while (pos !== -1) {
    if (pos > cursor) parts.push(text.slice(cursor, pos));
    parts.push(
      <Text key={key++} style={hitStyle}>
        {text.slice(pos, pos + kw.length)}
      </Text>,
    );
    cursor = pos + kw.length;
    pos = lower.indexOf(kw, cursor);
  }
  if (cursor < text.length) parts.push(text.slice(cursor));
  return parts;
}
export const TransactionCard = React.memo(function TransactionCard({ transaction, onPress, categoryId, showDate = true, highlight }: 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={ICON_SIZE} />
      <View style={styles.body}>
        <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, fontWeight: '600' }]} numberOfLines={1}>
          {highlightText(transaction.narration || transaction.payee || t('transaction.noSummary'), highlight, theme.colors.accent)}
        </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: theme.typography.body.fontSize - 1, 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', fontSize: theme.typography.caption.fontSize - 1, borderRadius: theme.radii.sm / 2 }]}>
              #{tag}
            </Text>
          ))}
        </View>
      )}
    </Touchable>
  );
});

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