/**
 * 交易页（spec §7.2）：搜索优先 + 日期分组时间线。
 * 搜索框常驻；方向 chip；高级筛选收进 FilterSheet（账户/日期/金额区间）；
 * 列表按日期分组（今天/昨天/具体日期 + 当日收支小计）；左滑复制/删除。
 * 解析诊断已移至 我的 → 数据 → 解析诊断（/settings/diagnostics）。
 */
import React, { useCallback, useMemo, useState } from 'react';
import { Pressable, SectionList, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useLedgerStore } from '../../store/ledgerStore';
import { useMetadataStore } from '../../store/metadataStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useNumpadUiStore } from '../../store/numpadUiStore';
import { useTheme, createCommonStyles } from '../../theme';
import { useT } from '../../i18n';
import { SearchBar } from '../../components/ui/SearchBar';
import { FilterSheet, type AdvancedFilterValues } from '../../components/form/FilterSheet';
import { SwipeableTransactionCard } from '../../components/transaction/SwipeableTransactionCard';
import { groupTransactionsByDate } from '../../components/transaction/transactionGroups';
import { useSearch, type SearchFilters } from '../../hooks/useSearch';
import { toDateString } from '../../domain/core/decimal';
import type { Transaction } from '../../domain/core/types';
import { EmptyState } from '../../components/ui/EmptyState';
import { useToast } from '../../components/ui/Toast';

type DirectionFilter = 'all' | 'expense' | 'income' | 'transfer';

const EMPTY_FILTERS: AdvancedFilterValues = { account: '', dateFrom: '', dateTo: '', amountMin: '', amountMax: '' };

export default function TransactionsScreen() {
  const { theme } = useTheme();
  const commonStyles = useMemo(() => createCommonStyles(theme), [theme]);
  const t = useT();
  const { showToast } = useToast();
  const router = useRouter();
  const ledger = useLedgerStore(s => s.ledger);
  const deleteTransaction = useLedgerStore(s => s.deleteTransaction);
  const restoreTransaction = useLedgerStore(s => s.restoreTransaction);
  const categories = useMetadataStore(s => s.categories);
  const recentSearches = useSettingsStore(s => s.recentSearches);
  const addRecentSearch = useSettingsStore(s => s.addRecentSearch);
  const clearRecentSearches = useSettingsStore(s => s.clearRecentSearches);

  const [keyword, setKeyword] = useState('');
  const [direction, setDirection] = useState<DirectionFilter>('all');
  const [filterSheetOpen, setFilterSheetOpen] = useState(false);
  const [advanced, setAdvanced] = useState<AdvancedFilterValues>(EMPTY_FILTERS);

  // 性能说明：每次 ledger 变化时全量重排序 O(n log n)。
  // 当前可接受：移动端账本通常 < 5000 笔，排序耗时 < 10ms。
  // 若未来数据量增大，可考虑：
  //   1. 在 ledgerStore 层维护已排序的 transactions 数组
  //   2. 新增交易时使用二分插入而非全量重排
  const allTransactions = useMemo(() => {
    if (!ledger?.transactions) return [];
    return ledger.transactions
      .map((tx, idx) => ({ tx, idx }))
      .sort((a, b) => b.tx.date.localeCompare(a.tx.date) || b.idx - a.idx)
      .map(item => item.tx);
  }, [ledger]);

  const filters: SearchFilters = useMemo(() => ({
    keyword: keyword || undefined,
    direction: direction === 'all' ? undefined : direction,
    account: advanced.account || undefined,
    dateFrom: advanced.dateFrom || undefined,
    dateTo: advanced.dateTo || undefined,
    amountMin: advanced.amountMin || undefined,
    amountMax: advanced.amountMax || undefined,
  }), [keyword, direction, advanced]);

  const filtered = useSearch(allTransactions, filters);
  const sections = useMemo(() =>
    groupTransactionsByDate(filtered).map(g => ({ ...g, data: g.items })),
  [filtered]);

  const advancedActive = advanced.account !== '' || advanced.dateFrom !== '' || advanced.dateTo !== '' || advanced.amountMin !== '' || advanced.amountMax !== '';

  const todayStr = toDateString(new Date());
  const yesterdayStr = toDateString(new Date(Date.now() - 86400000));
  const dateLabel = (date: string) =>
    date === todayStr ? t('transactions.today') : date === yesterdayStr ? t('transactions.yesterday') : date;

  const categoryIdFor = useCallback((tx: Transaction): string | undefined => {
    const target = tx.postings.find(p => p.account.startsWith('Expenses') || p.account.startsWith('Income'))?.account;
    return target ? categories.find(c => c.linkedAccount === target)?.id : undefined;
  }, [categories]);

  // 左滑：复制（预填今天的录入页）
  const handleDuplicate = (tx: Transaction) => {
    const draftJson = JSON.stringify({
      date: todayStr,
      payee: tx.payee,
      narration: tx.narration,
      tags: tx.tags,
      // cost/price 不带：复制是新建交易，丢 cost 属可接受简化（含 cost 的交易可从编辑入口进高级模式）
      postings: tx.postings.map(p => ({ account: p.account, amount: p.amount, currency: p.currency })),
    });
    useNumpadUiStore.getState().open({ draftJson });
  };

  // 左滑：删除（确认后从 main.bean 移除）
  // 删除：非阻断 toast + 撤销（取代阻断式 Alert 确认）
  const handleDelete = (tx: Transaction) => {
    const name = tx.narration || tx.payee || tx.date.slice(0, 10);
    deleteTransaction(tx.raw)
      .then(() => {
        showToast(t('transactions.deleted', { name }), 'success', {
          label: t('common.undo'),
          onPress: () => {
            restoreTransaction(tx.raw).catch(e => showToast(String(e), 'error'));
          },
        });
      })
      .catch(e => showToast(String(e), 'error'));
  };

  const directionTabs: { key: DirectionFilter; label: string }[] = [
    { key: 'all', label: t('transactions.filterAll') },
    { key: 'expense', label: t('transactions.filterExpense') },
    { key: 'income', label: t('transactions.filterIncome') },
    { key: 'transfer', label: t('transactions.filterTransfer') },
  ];

  return (
    <SafeAreaView style={[styles.page, { backgroundColor: theme.colors.bgPrimary }]} edges={['top']}>
      <View style={styles.header}>
        <Text style={[theme.typography.h1, { color: theme.colors.fgPrimary }]}>{t('tab.transactions')}</Text>
      </View>

      <SearchBar value={keyword} onChangeText={setKeyword} placeholder={t('transactions.searchPlaceholder')} onSubmit={() => addRecentSearch(keyword)} />
      {keyword.trim() === '' && recentSearches.length > 0 && (
        <View style={[{ flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', gap: 8, paddingHorizontal: 16, marginBottom: 8 }]}>
          <Ionicons name="time-outline" size={14} color={theme.colors.fgSecondary} />
          {recentSearches.map(s => (
            <Pressable key={s} onPress={() => setKeyword(s)} style={commonStyles.chip}>
              <Text style={commonStyles.chipText}>{s}</Text>
            </Pressable>
          ))}
          <Pressable onPress={() => clearRecentSearches()} hitSlop={8} accessibilityRole="button" accessibilityLabel={t('transactions.clearHistory')}>
            <Ionicons name="close-circle-outline" size={16} color={theme.colors.fgSecondary} />
          </Pressable>
        </View>
      )}

      {/* 方向筛选 + 高级筛选入口 */}
      <View style={styles.filterRow}>
        {directionTabs.map(tab => (
          <Pressable key={tab.key} onPress={() => setDirection(tab.key)}
            style={[commonStyles.chip, direction === tab.key && commonStyles.chipActive]}>
            <Text style={[commonStyles.chipText, direction === tab.key && commonStyles.chipTextActive]}>{tab.label}</Text>
          </Pressable>
        ))}
        <View style={styles.flex1} />
        <Pressable
          onPress={() => setFilterSheetOpen(true)}
          style={[commonStyles.chip, advancedActive && commonStyles.chipActive, styles.filterBtn]}
          accessibilityRole="button"
          accessibilityLabel={t('transactions.filter')}
        >
          <Ionicons name="options-outline" size={14} color={advancedActive ? theme.colors.fgInverse : theme.colors.fgSecondary} />
          <Text style={[commonStyles.chipText, advancedActive && commonStyles.chipTextActive]}>{t('transactions.filter')}</Text>
        </Pressable>
      </View>

      <SectionList
        sections={sections}
        keyExtractor={(item, index) => `${item.id}-${index}`}
        renderItem={({ item: tx }) => (
          <SwipeableTransactionCard
            transaction={tx}
            categoryId={categoryIdFor(tx)}
            showDate={false}
            highlight={keyword}
            onPress={() => router.push(`/transaction/${tx.id}`)}
            onDuplicate={handleDuplicate}
            onDelete={handleDelete}
          />
        )}
        renderSectionHeader={({ section }) => (
          <View style={styles.sectionHeader}>
            <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary, fontWeight: '700' }]}>
              {dateLabel(section.date)}
            </Text>
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, fontVariant: ['tabular-nums'] }]}>
              {t('transactions.daySummary', { income: `+${section.income}`, expense: `-${section.expense}` })}
            </Text>
          </View>
        )}
        ListHeaderComponent={
          <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, paddingBottom: 8 }]}>
            {filtered.length === allTransactions.length
              ? t('transactions.countTotal', { count: filtered.length })
              : t('transactions.countFiltered', { shown: filtered.length, total: allTransactions.length })}
          </Text>
        }
        ListEmptyComponent={
          <EmptyState
            icon={allTransactions.length === 0 ? 'receipt-outline' : 'search-outline'}
            title={t('transactions.noMatchTitle')}
            description={allTransactions.length === 0 ? t('transactions.noMatchEmpty') : t('transactions.noMatchFiltered')}
          />
        }
        contentContainerStyle={styles.content}
        stickySectionHeadersEnabled={false}
        initialNumToRender={10}
        maxToRenderPerBatch={10}
        windowSize={5}
      />

      <FilterSheet
        visible={filterSheetOpen}
        onClose={() => setFilterSheetOpen(false)}
        values={advanced}
        onChange={setAdvanced}
        onReset={() => setAdvanced(EMPTY_FILTERS)}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  page: { flex: 1 },
  header: { paddingHorizontal: 16, paddingTop: 8, paddingBottom: 8 },
  filterRow: { flexDirection: 'row', gap: 6, paddingHorizontal: 16, paddingBottom: 8, alignItems: 'center' },
  filterBtn: { flexDirection: 'row', alignItems: 'center', gap: 4 },
  flex1: { flex: 1 },
  content: { padding: 16, paddingTop: 8 },
  sectionHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingVertical: 8 },
});
