/**
 * 规则管理页面（plan.md「1.1 rules」+ 自动分类规则）。
 *
 * 功能：规则列表(匹配条件 → 分类账户) + 添加/编辑/删除。
 * 规则用于 BillPipeline 的自动分类(参考 AutoAccounting RuleGenerator)。
 * P5：套 ManagementScreen 模板，消除手写头部/新增按钮/弹窗样板。
 */
import React from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { useMetadataStore, generateId } from '../../store/metadataStore';
import { Card } from '../../components/ui/Card';
import { ManagementScreen } from '../../components/layout/ManagementScreen';
import type { Rule } from '../../domain/core/types';

export default function RulesScreen() {
  const { theme } = useTheme();
  const t = useT();

  const rules = useMetadataStore(s => s.rules);
  const addRule = useMetadataStore(s => s.addRule);
  const updateRule = useMetadataStore(s => s.updateRule);
  const removeRule = useMetadataStore(s => s.removeRule);

  const formatCondition = (rule: Rule): string => {
    const parts: string[] = [];
    if (rule.counterpartyContains) parts.push(t('rules.condCounterparty', { val: rule.counterpartyContains }));
    if (rule.memoContains) parts.push(t('rules.condMemo', { val: rule.memoContains }));
    return parts.length > 0 ? parts.join(' · ') : t('rules.condNone');
  };

  return (
    <ManagementScreen<Rule>
      title={t('tab.rules')}
      items={[...rules].sort((a, b) => b.priority - a.priority)}
      keyExtractor={rule => rule.id}
      addLabel={t('rules.add')}
      emptyText={t('rules.empty')}
      renderItem={(rule, { openEdit, confirmDelete }) => (
        <Card>
          <Pressable
            onPress={openEdit}
            onLongPress={confirmDelete}
            style={({ pressed }) => [{ opacity: pressed ? 0.6 : 1 }]}
          >
            <View style={styles.ruleHeader}>
              <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, fontWeight: '600' }]}>{rule.narration || rule.id}</Text>
              <Text style={[theme.typography.caption, { color: theme.colors.accent }]}>P{rule.priority}</Text>
            </View>
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
              {formatCondition(rule)}
            </Text>
            <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4, marginTop: 2 }}>
              <Ionicons name="arrow-forward-outline" size={12} color={theme.colors.fgSecondary} />
              <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
                {rule.categoryAccount} ({t('rules.hitsSuffix', { count: rule.hits })})
              </Text>
            </View>
          </Pressable>
        </Card>
      )}
      formTitle={editing => (editing ? t('rules.editTitle') : t('rules.add'))}
      formFields={editing => [
        { key: 'priority', label: t('rules.fieldPriority'), placeholder: '100', defaultValue: editing ? String(editing.priority) : '', keyboardType: 'numeric' },
        { key: 'counterpartyContains', label: t('rules.fieldCounterparty'), placeholder: '咖啡', defaultValue: editing?.counterpartyContains ?? '' },
        { key: 'memoContains', label: t('rules.fieldMemo'), placeholder: '', defaultValue: editing?.memoContains ?? '' },
        { key: 'sourceAccount', label: t('rules.fieldSourceAccount'), placeholder: 'Assets:支付宝余额', defaultValue: editing?.sourceAccount ?? '' },
        { key: 'categoryAccount', label: t('rules.fieldCategoryAccount'), placeholder: 'Expenses:餐饮', defaultValue: editing?.categoryAccount ?? '' },
        { key: 'narration', label: t('rules.fieldNarration'), placeholder: '咖啡', defaultValue: editing?.narration ?? '' },
        { key: 'tags', label: t('rules.fieldTags'), placeholder: 'food', defaultValue: editing?.tags?.join(', ') ?? '' },
      ]}
      onSubmit={(values, editing) => {
        const rule: Omit<Rule, 'id' | 'hits'> = {
          priority: parseInt(values.priority, 10) || 0,
          counterpartyContains: values.counterpartyContains?.trim() || undefined,
          memoContains: values.memoContains?.trim() || undefined,
          sourceAccount: values.sourceAccount?.trim() || 'Assets:Unknown',
          categoryAccount: values.categoryAccount?.trim() || 'Expenses:未分类',
          narration: values.narration?.trim() || undefined,
          tags: values.tags ? values.tags.split(/[,，\s]+/).filter(Boolean) : [],
        };
        if (editing) {
          updateRule(editing.id, rule);
        } else {
          addRule({ ...rule, id: generateId('rule'), hits: 0 });
        }
        return true;
      }}
      onDelete={rule => removeRule(rule.id)}
      deleteConfirmText={rule => t('rules.deleteConfirm', { name: rule.id })}
      deleteConfirmTitle={t('rules.deleteTitle')}
      footer={
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, textAlign: 'center' }]}>
          {t('common.clickEditLongDelete')}
        </Text>
      }
    />
  );
}

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