import React, { useMemo, useState, useEffect, useRef } from 'react';
import { ScrollView, StyleSheet, Text, TextInput, View, Switch, Alert, Pressable, LayoutAnimation, Platform } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams, useNavigation } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system/legacy';
import { useLedgerStore } from '../../store/ledgerStore';
import { useMetadataStore } from '../../store/metadataStore';
import { useTheme, createCommonStyles } from '../../theme';
import { useT } from '../../i18n';
import { Card } from '../../components/Card';
import { Button } from '../../components/Button';
import { CategoryPicker } from '../../components/CategoryPicker';
import { TagPicker } from '../../components/TagPicker';
import { PostingEditor } from '../../components/PostingEditor';
import { tagsToBeanSyntax } from '../../domain/tags';
import { serializeTransaction } from '../../domain/ledger';
import { buildAndSaveTransaction } from '../../domain/transactionBuilder';
import { matchCategory } from '../../domain/categories';
import { getNativeOcrModule, getNativeOcrBridge } from '../../services/ocrBridge';
import { OcrProcessor } from '../../domain/ocrProcessor';
import type { Category } from '../../domain/categories';
import type { Tag } from '../../domain/tags';
import type { Posting } from '../../domain/types';


type Direction = 'expense' | 'income' | 'transfer';

export default function NewTransactionScreen() {
  const { theme } = useTheme();
  const commonStyles = createCommonStyles(theme);
  const t = useT();
  const router = useRouter();
  const { mode, editId, draftJson } = useLocalSearchParams<{ mode?: string; editId?: string; draftJson?: string }>();
  const addTransaction = useLedgerStore(s => s.addTransaction);
  const editTransaction = useLedgerStore(s => s.editTransaction);
  const ledger = useLedgerStore(s => s.ledger);
  const categories = useMetadataStore(s => s.categories);
  const tags = useMetadataStore(s => s.tags);

  const today = new Date().toISOString().slice(0, 10);

  // 基础表单状态
  const [date, setDate] = useState(today);
  const [narration, setNarration] = useState('');
  const [payee, setPayee] = useState('');
  const [currency, setCurrency] = useState('CNY');
  const [amount, setAmount] = useState('');
  const [direction, setDirection] = useState<Direction>('expense');
  const [sourceAccount, setSourceAccount] = useState('Assets:支付宝余额');
  const [targetAccount, setTargetAccount] = useState('Assets:微信零钱');
  const [selectedCategory, setSelectedCategory] = useState<Category | null>(null);
  const [selectedTags, setSelectedTags] = useState<Tag[]>([]);
  const [status, setStatus] = useState('');

  // 高级模式状态
  const [isAdvanced, setIsAdvanced] = useState(false);
  const [showDetails, setShowDetails] = useState(false);

  const [postings, setPostings] = useState<Posting[]>([
    { account: 'Assets:支付宝余额', amount: '', currency: 'CNY' },
    { account: 'Expenses:餐饮', amount: '', currency: 'CNY' }
  ]);

  const [isSubmitted, setIsSubmitted] = useState(false);
  const navigation = useNavigation();

  useEffect(() => {
    const unsubscribe = navigation.addListener('beforeRemove', (e) => {
      const hasChanges =
        amount.trim() !== '' ||
        payee.trim() !== '' ||
        narration.trim() !== '' ||
        selectedTags.length > 0 ||
        (isAdvanced && postings.some(p => p.account.trim() !== '' || (p.amount || '').trim() !== ''));

      if (!hasChanges || isSubmitted) {
        return;
      }

      e.preventDefault();
      Alert.alert(
        t('transaction.unsavedTitle'),
        t('transaction.unsavedMessage'),
        [
          { text: t('common.cancel'), style: 'cancel', onPress: () => {} },
          {
            text: t('common.discard'),
            style: 'destructive',
            onPress: () => navigation.dispatch(e.data.action),
          },
        ]
      );
    });

    return unsubscribe;
  }, [navigation, amount, payee, narration, selectedTags, postings, isAdvanced, isSubmitted]);

  // === 草稿预填模式 ===
  useEffect(() => {
    if (draftJson) {
      try {
        const draft = JSON.parse(draftJson);
        setDate(draft.date ? draft.date.slice(0, 10) : today);
        setNarration(draft.narration || '');
        setPayee(draft.payee || '');
        
        const expensePosting = draft.postings.find((p: any) => p.account.startsWith('Expenses'));
        const incomePosting = draft.postings.find((p: any) => p.account.startsWith('Income'));
        const assetsPostings = draft.postings.filter((p: any) => p.account.startsWith('Assets') || p.account.startsWith('Liabilities'));

        if (expensePosting) {
          setDirection('expense');
          setCurrency(expensePosting.currency || 'CNY');
          setAmount((expensePosting.amount || '').replace(/^-/, ''));
          const matchedCat = categories.find(c => c.linkedAccount === expensePosting.account);
          if (matchedCat) setSelectedCategory(matchedCat);
          if (assetsPostings.length > 0) {
            setSourceAccount(assetsPostings[0].account);
          }
        } else if (incomePosting) {
          setDirection('income');
          setCurrency(incomePosting.currency || 'CNY');
          setAmount((incomePosting.amount || '').replace(/^-/, ''));
          const matchedCat = categories.find(c => c.linkedAccount === incomePosting.account);
          if (matchedCat) setSelectedCategory(matchedCat);
          if (assetsPostings.length > 0) {
            setSourceAccount(assetsPostings[0].account);
          }
        } else {
          setDirection('transfer');
          if (draft.postings.length >= 2) {
            setCurrency(draft.postings[0].currency || 'CNY');
            setAmount((draft.postings[0].amount || '').replace(/^-/, ''));
            setSourceAccount(draft.postings[0].account);
            setTargetAccount(draft.postings[1].account);
          }
        }

        if (draft.postings && draft.postings.length > 0) {
          setPostings(draft.postings.map((p: any) => ({
            account: p.account,
            amount: p.amount,
            currency: p.currency,
            cost: p.cost,
            price: p.price,
            metadata: p.metadata,
          })));
        }
      } catch (e) {
        console.error('Failed to parse draftJson', e);
      }
    }
  }, [draftJson, categories]);

  // === 编辑模式：预填表单 ===
  const editingTx = useMemo(
    () => editId ? ledger?.transactions.find(txn => txn.id === editId) : undefined,
    [editId, ledger],
  );
  const [oldRaw, setOldRaw] = useState('');
  const [editFlag, setEditFlag] = useState<string>('*');
  const [editLinks, setEditLinks] = useState<string[]>([]);
  const [editMetadata, setEditMetadata] = useState<Record<string, string> | undefined>(undefined);
  useEffect(() => {
    if (editingTx) {
      setOldRaw(editingTx.raw);
      setDate(editingTx.date.slice(0, 10));
      setNarration(editingTx.narration || '');
      setPayee(editingTx.payee || '');
      setCurrency(editingTx.postings[0]?.currency || 'CNY');
      // 保留编辑前的 flag/links/metadata
      setEditFlag(editingTx.flag || '*');
      setEditLinks(editingTx.links || []);
      setEditMetadata(editingTx.metadata);
      // 从 postings 推断方向和金额
      const expensePosting = editingTx.postings.find(p => p.account.startsWith('Expenses'));
      const incomePosting = editingTx.postings.find(p => p.account.startsWith('Income'));
      if (expensePosting) {
        setDirection('expense');
        setAmount(expensePosting.amount?.replace(/^-/, '') || '');
        setSourceAccount(editingTx.postings.find(p => p.account.startsWith('Assets'))?.account || 'Assets:Alipay');
        // 预填分类：匹配 Expenses 账户对应的 category
        const matchedCat = categories.find(c => c.linkedAccount === expensePosting.account);
        if (matchedCat) setSelectedCategory(matchedCat);
      } else if (incomePosting) {
        setDirection('income');
        setAmount(incomePosting.amount?.replace(/^-/, '') || '');
        setSourceAccount(editingTx.postings.find(p => p.account.startsWith('Assets'))?.account || 'Assets:Alipay');
        // 预填分类
        const matchedCat = categories.find(c => c.linkedAccount === incomePosting.account);
        if (matchedCat) setSelectedCategory(matchedCat);
      } else {
        setDirection('transfer');
        setAmount(editingTx.postings[0]?.amount?.replace(/^-/, '') || '');
        setSourceAccount(editingTx.postings[0]?.account || '');
        setTargetAccount(editingTx.postings[1]?.account || '');
      }
      // 预填 postings（高级模式，含 cost/price/metadata）
      setPostings(editingTx.postings.map(p => ({
        account: p.account,
        amount: p.amount,
        currency: p.currency,
        cost: p.cost,
        price: p.price,
        metadata: p.metadata,
      })));
      // 预填标签
      if (editingTx.tags.length > 0) {
        setSelectedTags(editingTx.tags.map(name => ({ id: name, name, color: '#2196F3' })));
      }
    }
  }, [editingTx, categories]);

  // 按方向过滤分类
  const availableCategories = useMemo(
    () => categories.filter(c => c.type === (direction === 'income' ? 'income' : 'expense')),
    [categories, direction],
  );

  // 来源账户列表(从 ledger 提取 Assets 账户)
  const assetAccounts = useMemo(() => {
    if (!ledger) return ['Assets:支付宝余额', 'Assets:微信零钱', 'Assets:兴业银行储蓄卡-2586'];
    const accts = Array.from(ledger.accounts.keys()).filter(a => a.startsWith('Assets'));
    return accts.length > 0 ? accts : ['Assets:支付宝余额'];
  }, [ledger]);

  const toggleTag = (tag: Tag) => {
    setSelectedTags(prev =>
      prev.some(t => t.name === tag.name)
        ? prev.filter(t => t.name !== tag.name)
        : [...prev, tag],
    );
  };

  // === OCR 拍照识账 ===
  const handleOcrScan = async () => {
    try {
      // 1. 选图（相册或拍照）
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: false,
        quality: 0.8,
        base64: true,
      });
      if (result.canceled || !result.assets?.[0]?.base64) return;

      const base64 = result.assets[0].base64;

      // 2. 检查 OCR 引擎是否就绪
      const nativeModule = getNativeOcrModule();
      if (nativeModule) {
        const ready = await nativeModule.isReady();
        if (!ready) {
          Alert.alert(t('ocr.notReady'));
          return;
        }
      }

      setStatus(t('ocr.scanning'));

      // 3. 走 OcrProcessor 管线 (Layer1 regex → Layer2 → Layer3 AI)
      const ocrBridge = getNativeOcrBridge();
      const processor = new OcrProcessor(ocrBridge);
      const ocrResult = await processor.process(base64);

      if (ocrResult.event) {
        // 4. 预填表单
        const event = ocrResult.event;
        if (event.amount) {
          const absAmount = event.amount.replace(/^-/, '');
          setAmount(absAmount);
        }
        if (event.counterparty || event.memo) {
          setNarration([event.counterparty, event.memo].filter(Boolean).join(' - '));
        }
        if (event.direction === 'income') {
          setDirection('income');
        } else if (event.direction === 'transfer') {
          setDirection('transfer');
        } else {
          setDirection('expense');
        }
        // 5. 自动分类：根据商户名/备注匹配分类（与 BillPipeline 分类逻辑一致）
        const matchText = [event.counterparty, event.memo].filter(Boolean).join(' ');
        if (matchText) {
          const type = event.direction === 'income' ? 'income' : 'expense';
          const candidates = categories.filter(c => c.type === type);
          const match = matchCategory(matchText, candidates);
          if (match.category) {
            setSelectedCategory(match.category);
          }
        }
        setStatus(t('ocr.success'));
      } else {
        setStatus(t('ocr.failed'));
      }
    } catch (e) {
      setStatus(t('ocr.failed') + ': ' + (e instanceof Error ? e.message : String(e)));
    }
  };

  // 从 SpeedDial OCR 入口进入时自动触发
  useEffect(() => {
    if (mode === 'ocr') {
      handleOcrScan();
    }
  }, [mode]);

  const submit = () => {
    const tagNames = selectedTags.map(tg => tg.name);

    if (isAdvanced) {
      // 高级模式：校验多 postings
      const validPostings = postings.filter(p => p.account.trim());
      if (validPostings.length < 2) {
        setStatus(t('transaction.atLeast2Postings'));
        return;
      }

      // 实时借贷平衡验证
      const currencySum: Record<string, number> = {};
      for (const p of validPostings) {
        if (p.amount && p.currency) {
          const val = parseFloat(p.amount);
          if (!isNaN(val)) {
            currencySum[p.currency] = (currencySum[p.currency] || 0) + val;
          }
        }
      }

      const isBalanced = Object.values(currencySum).every(sum => Math.abs(sum) < 0.001);
      if (!isBalanced) {
        setStatus(t('transaction.unbalanced'));
        return;
      }

      const draft = {
        date,
        flag: editId ? editFlag : undefined,
        narration: narration.trim() || t('transaction.defaultAdvancedNarration'),
        postings: validPostings,
        tags: tagNames,
        links: editId && editLinks.length > 0 ? editLinks : undefined,
        metadata: editId ? editMetadata : undefined,
      };

      if (editId && oldRaw) {
        // 编辑模式：序列化新内容并替换旧块
        const newRaw = serializeTransaction(draft);
        editTransaction(oldRaw, newRaw).then(() => {
          setIsSubmitted(true);
          setStatus(t('transaction.editSuccess'));
          setTimeout(() => router.back(), 600);
        }).catch(e => setStatus(String(e)));
      } else {
        addTransaction(draft).then(() => {
          setIsSubmitted(true);
          setStatus(t('transaction.appended'));
          setNarration('');
          setSelectedTags([]);
          setTimeout(() => router.back(), 600);
        }).catch(e => setStatus(String(e)));
      }

    } else {
      // 简单模式：调用统一的 buildAndSaveTransaction 构建复式 postings 并保存
      const amt = amount.trim();
      if (!amt) {
        setStatus(t('transaction.amountRequired'));
        return;
      }

      if (direction === 'transfer' && sourceAccount === targetAccount) {
        setStatus(t('transaction.sameAccountError'));
        return;
      }

      const categoryAccount = selectedCategory?.linkedAccount ?? 'Expenses:Uncategorized';

      if (editId && oldRaw) {
        // 编辑模式：由于编辑模式需要保留原始元数据并替换原始代码块，我们仍然就地拼装 draft 并执行 editTransaction
        let finalPostings: Posting[];
        if (direction === 'expense') {
          finalPostings = [
            { account: sourceAccount, amount: `-${amt}`, currency },
            { account: categoryAccount, amount: amt, currency },
          ];
        } else if (direction === 'income') {
          finalPostings = [
            { account: sourceAccount, amount: amt, currency },
            { account: categoryAccount, amount: `-${amt}`, currency },
          ];
        } else {
          finalPostings = [
            { account: sourceAccount, amount: `-${amt}`, currency },
            { account: targetAccount, amount: amt, currency },
          ];
        }

        const draft = {
          date,
          payee: payee.trim() || undefined,
          flag: editFlag,
          narration: narration.trim() || (
            direction === 'expense' ? t('transaction.narrationDefaultExpense') :
            direction === 'income' ? t('transaction.narrationDefaultIncome') :
            t('transaction.narrationDefaultTransfer')
          ),
          postings: finalPostings,
          tags: tagNames,
          links: editLinks.length > 0 ? editLinks : undefined,
          metadata: editMetadata,
        };

        const newRaw = serializeTransaction(draft);
        editTransaction(oldRaw, newRaw).then(() => {
          setIsSubmitted(true);
          setStatus(t('transaction.editSuccess'));
          setTimeout(() => router.back(), 600);
        }).catch(e => setStatus(String(e)));
      } else {
        // 新建交易：直接调用统一的共享逻辑函数
        buildAndSaveTransaction({
          date,
          amount: amt,
          payee: payee.trim() || undefined,
          narration: narration.trim() || (
            direction === 'expense' ? t('transaction.narrationDefaultExpense') :
            direction === 'income' ? t('transaction.narrationDefaultIncome') :
            t('transaction.narrationDefaultTransfer')
          ),
          categoryAccount: direction === 'transfer' ? targetAccount : categoryAccount,
          sourceAccount,
          direction,
          currency,
          tags: tagNames,
          links: editLinks.length > 0 ? editLinks : undefined,
          metadata: editMetadata,
        }).then(() => {
          setIsSubmitted(true);
          setStatus(t('transaction.appended'));
          setAmount('');
          setNarration('');
          setSelectedCategory(null);
          setSelectedTags([]);
          setTimeout(() => router.back(), 600);
        }).catch(e => setStatus(String(e)));
      }
    }
  };

  const directions: { key: Direction; label: string; color: string }[] = [
    { key: 'expense', label: t('transaction.directionExpense'), color: theme.colors.financial.expense },
    { key: 'income', label: t('transaction.directionIncome'), color: theme.colors.financial.income },
    { key: 'transfer', label: t('transaction.directionTransfer'), color: theme.colors.financial.transfer },
  ];

  return (
    <SafeAreaView style={[styles.page, { backgroundColor: theme.colors.bgPrimary }]} edges={['bottom', 'left', 'right']}>
      <ScrollView contentContainerStyle={[styles.content, { gap: theme.spacing.md }]}>
        {/* 高级模式模式切换开关 */}
        <View style={commonStyles.switchRow}>
          <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, fontWeight: '700', fontFamily: theme.typography.body.fontFamily }]}>
            {t('transaction.advancedMode')}
          </Text>
          <Switch
            value={isAdvanced}
            onValueChange={(val) => {
              setIsAdvanced(val);
              // 同步初始化当前分录
              if (val) {
                const amt = amount.trim();
                const categoryAccount = selectedCategory?.linkedAccount ?? 'Expenses:Uncategorized';
                if (direction === 'expense') {
                  setPostings([
                    { account: sourceAccount, amount: amt ? `-${amt}` : '', currency: 'CNY' },
                    { account: categoryAccount, amount: amt || '', currency: 'CNY' },
                  ]);
                } else if (direction === 'income') {
                  setPostings([
                    { account: sourceAccount, amount: amt || '', currency: 'CNY' },
                    { account: categoryAccount, amount: amt ? `-${amt}` : '', currency: 'CNY' },
                  ]);
                } else {
                  setPostings([
                    { account: sourceAccount, amount: amt ? `-${amt}` : '', currency: 'CNY' },
                    { account: targetAccount, amount: amt || '', currency: 'CNY' },
                  ]);
                }
              }
            }}
            trackColor={{ false: theme.colors.bgPrimary, true: theme.colors.accent }}
            thumbColor={theme.colors.fgInverse}
          />
        </View>

        {/* 简单模式下的方向选择 */}
        {!isAdvanced && (
          <View style={styles.directionRow}>
            {directions.map(d => (
              <Pressable
                key={d.key}
                onPress={() => { setDirection(d.key); setSelectedCategory(null); }}
                style={[
                  commonStyles.chip,
                  direction === d.key && commonStyles.chipActive,
                  { flex: 1, alignItems: 'center' }
                ]}
              >
                <Text style={[
                  commonStyles.chipText,
                  direction === d.key && commonStyles.chipTextActive,
                  { fontFamily: theme.typography.caption.fontFamily }
                ]}>
                  {d.label}
                </Text>
              </Pressable>
            ))}
            <Pressable
              onPress={handleOcrScan}
              style={[
                commonStyles.chip,
                { alignItems: 'center', minWidth: 60, borderColor: theme.colors.accent }
              ]}
            >
              <Text style={[commonStyles.chipText, { color: theme.colors.accent, fontFamily: theme.typography.caption.fontFamily }]}>
                {t('home.ocrScan')}
              </Text>
            </Pressable>
          </View>
        )}

        {/* 主输入区域：金额与账户 (简单模式) 或 分录编辑器 (高级模式) */}
        {!isAdvanced ? (
          <Card title={t('transaction.newTitle')}>
            {/* 金额 */}
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginBottom: 4, fontFamily: theme.typography.caption.fontFamily }]}>
              {t('transaction.amountPlaceholder')}
            </Text>
            <View style={{ flexDirection: 'row', gap: 8 }}>
              <TextInput
                value={amount}
                onChangeText={setAmount}
                autoFocus={editId ? false : true}
                keyboardType="decimal-pad"
                placeholder={t('transaction.amountPlaceholder')}
                placeholderTextColor={theme.colors.fgSecondary}
                style={[commonStyles.input, { flex: 1, fontFamily: 'monospace', fontSize: 16 }]}
              />
              <TextInput
                value={currency}
                onChangeText={setCurrency}
                placeholder="CNY"
                maxLength={3}
                autoCapitalize="characters"
                style={[commonStyles.input, { width: 70, textAlign: 'center' }]}
              />
            </View>

            {/* 来源账户 */}
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginBottom: 4, marginTop: 10, fontFamily: theme.typography.caption.fontFamily }]}>
              {t('transaction.formSourceAccount')}
            </Text>
            <TextInput
              value={sourceAccount}
              onChangeText={setSourceAccount}
              placeholder="Assets:支付宝余额"
              placeholderTextColor={theme.colors.fgSecondary}
              style={commonStyles.input}
            />

            {/* 快捷来源账户选择 */}
            <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
              {assetAccounts.map(acct => {
                const active = sourceAccount === acct;
                const shortName = acct.split(':').pop() || acct;
                return (
                  <Pressable
                    key={`src-${acct}`}
                    onPress={() => setSourceAccount(acct)}
                    style={[
                      commonStyles.chip,
                      active && { backgroundColor: theme.colors.accentLight, borderColor: theme.colors.accent },
                      { paddingVertical: 4, paddingHorizontal: 8 }
                    ]}
                  >
                    <Text style={[
                      commonStyles.chipText,
                      { fontSize: 11 },
                      active && { color: theme.colors.accent, fontWeight: '700' }
                    ]}>
                      {shortName}
                    </Text>
                  </Pressable>
                );
              })}
            </View>

            {/* 目标账户 (仅在转账时显示) */}
            {direction === 'transfer' && (
              <View style={{ marginTop: 10 }}>
                <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginBottom: 4, fontFamily: theme.typography.caption.fontFamily }]}>
                  {t('transaction.targetAccount')}
                </Text>
                <TextInput
                  value={targetAccount}
                  onChangeText={setTargetAccount}
                  placeholder="Assets:WeChat"
                  placeholderTextColor={theme.colors.fgSecondary}
                  style={commonStyles.input}
                />
                {/* 快捷目标账户选择 */}
                <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
                  {assetAccounts.map(acct => {
                    const active = targetAccount === acct;
                    const shortName = acct.split(':').pop() || acct;
                    return (
                      <Pressable
                        key={`tgt-${acct}`}
                        onPress={() => setTargetAccount(acct)}
                        style={[
                          commonStyles.chip,
                          active && { backgroundColor: theme.colors.accentLight, borderColor: theme.colors.accent },
                          { paddingVertical: 4, paddingHorizontal: 8 }
                        ]}
                      >
                        <Text style={[
                          commonStyles.chipText,
                          { fontSize: 11 },
                          active && { color: theme.colors.accent, fontWeight: '700' }
                        ]}>
                          {shortName}
                        </Text>
                      </Pressable>
                    );
                  })}
                </View>
              </View>
            )}
          </Card>
        ) : (
          <Card title={t('transaction.newTitle')}>
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginBottom: 8, fontFamily: theme.typography.caption.fontFamily }]}>
              {t('transaction.postingsList')}
            </Text>
            
            <PostingEditor 
              postings={postings} 
              onChange={(p) => setPostings(p)} 
            />
            
            <View style={styles.postingBtnRow}>
              <View style={{ flex: 1 }}>
                <Button
                  label={t('transaction.addPosting')}
                  onPress={() => setPostings([...postings, { account: '', amount: '', currency: 'CNY' }])}
                  variant="secondary"
                />
              </View>
              <View style={{ flex: 1 }}>
                <Button
                  label={t('transaction.deleteLastPosting')}
                  onPress={() => postings.length > 2 && setPostings(postings.slice(0, -1))}
                  variant="secondary"
                />
              </View>
            </View>
          </Card>
        )}

        {/* 简单模式下的分类选择 */}
        {!isAdvanced && direction !== 'transfer' && (
          <Card title={direction === 'income' ? t('transaction.formCategoryIncome') : t('transaction.formCategoryExpense')}>
            <CategoryPicker
              categories={availableCategories}
              selectedId={selectedCategory?.id}
              onSelect={(cat) => setSelectedCategory(cat)}
            />
            {selectedCategory && (
              <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4, marginTop: 8 }}>
                <Ionicons name="arrow-forward-outline" size={12} color={theme.colors.fgSecondary} />
                <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, fontFamily: theme.typography.caption.fontFamily }]}>
                  {selectedCategory.linkedAccount}
                </Text>
              </View>
            )}
          </Card>
        )}

        {/* 详情与高级字段收纳区 */}
        <Pressable
          onPress={() => {
            LayoutAnimation.easeInEaseOut();
            setShowDetails(!showDetails);
          }}
          style={({ pressed }) => [
            styles.detailsToggle,
            {
              borderColor: theme.colors.border,
              backgroundColor: theme.colors.bgSecondary,
              opacity: pressed ? 0.8 : 1,
              flexDirection: 'row',
              gap: 6
            }
          ]}
        >
          <Text style={[theme.typography.bodySmall, { color: theme.colors.accent, fontWeight: '700', fontFamily: theme.typography.bodySmall.fontFamily }]}>
            {showDetails ? t('transaction.hideDetails') : t('transaction.addDetails')}
          </Text>
          <Ionicons
            name={showDetails ? 'chevron-up-outline' : 'chevron-down-outline'}
            size={16}
            color={theme.colors.accent}
          />
        </Pressable>

        {showDetails && (
          <View style={{ gap: theme.spacing.md }}>
            <Card title={t('transaction.extraDetails')}>
              {/* 日期 */}
              <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginBottom: 4, fontFamily: theme.typography.caption.fontFamily }]}>
                {t('transaction.formDate')}
              </Text>
              <TextInput
                value={date}
                onChangeText={setDate}
                placeholder="YYYY-MM-DD"
                placeholderTextColor={theme.colors.fgSecondary}
                style={commonStyles.input}
              />

              {/* 摘要 */}
              <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginBottom: 4, marginTop: 10, fontFamily: theme.typography.caption.fontFamily }]}>
                {t('transaction.formNarration')}
              </Text>
              <TextInput
                value={narration}
                onChangeText={setNarration}
                placeholder={t('transaction.formNarration')}
                placeholderTextColor={theme.colors.fgSecondary}
                style={commonStyles.input}
              />

              {/* 收款方（简单模式才显示） */}
              {!isAdvanced && (
                <>
                  <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginBottom: 4, marginTop: 10, fontFamily: theme.typography.caption.fontFamily }]}>
                    {t('transaction.formPayee')}
                  </Text>
                  <TextInput
                    value={payee}
                    onChangeText={setPayee}
                    placeholder={t('transaction.formPayeePlaceholder')}
                    placeholderTextColor={theme.colors.fgSecondary}
                    style={commonStyles.input}
                  />
                </>
              )}
            </Card>

            {/* 标签选择 */}
            <Card title={t('transaction.formTags')}>
              <TagPicker
                tags={tags}
                selectedNames={selectedTags.map(tg => tg.name)}
                onToggle={toggleTag}
              />
              {selectedTags.length > 0 && (
                <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginTop: 8, fontFamily: theme.typography.caption.fontFamily }]}>
                  {t('transaction.formTagsWillWrite')}: {tagsToBeanSyntax(selectedTags)}
                </Text>
              )}
            </Card>
          </View>
        )}

        <Button label={t('transaction.submit')} onPress={submit} />
        {status ? <Text style={[theme.typography.bodySmall, { color: theme.colors.fgSecondary, textAlign: 'center', marginTop: 8, fontFamily: theme.typography.bodySmall.fontFamily }]}>{status}</Text> : null}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  page: { flex: 1 },
  content: { padding: 16, paddingBottom: 40 },
  directionRow: { flexDirection: 'row', gap: 8, marginBottom: 4 },
  postingBtnRow: { flexDirection: 'row', gap: 8, marginTop: 8 },
  detailsToggle: { paddingVertical: 12, paddingHorizontal: 16, borderRadius: 12, borderWidth: StyleSheet.hairlineWidth, alignItems: 'center', justifyContent: 'center', marginTop: 4 },
});
