/**
 * 交易页（spec §7.2）：搜索优先 + 日期分组时间线。
 * 搜索框常驻；方向 chip；高级筛选收进 FilterSheet（账户/日期/金额区间）；
 * 列表按日期分组（今天/昨天/具体日期 + 当日收支小计）；左滑复制/删除。
 * 解析诊断已移至 我的 → 数据 → 解析诊断（/settings/diagnostics）。
 */
import React, { useMemo, useState } from 'react';
import { Alert, 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 { useNumpadUiStore } from '../../store/numpadUiStore';
import { useTheme, createCommonStyles } from '../../theme';
import { useT } from '../../i18n';
import { Card } from '../../components/Card';
import { SearchBar } from '../../components/SearchBar';
import { FilterSheet, type AdvancedFilterValues } from '../../components/FilterSheet';
import { SwipeableTransactionCard } from '../../components/SwipeableTransactionCard';
import { groupTransactionsByDate } from '../../components/transactionGroups';
import { useSearch, type SearchFilters } from '../../hooks/useSearch';
import { toDateString } from '../../domain/decimal';
import type { Transaction } from '../../domain/types';

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 router = useRouter();
  const ledger = useLedgerStore(s => s.ledger);
  const deleteTransaction = useLedgerStore(s => s.deleteTransaction);
  const categories = useMetadataStore(s => s.categories);

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

  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 = (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;
  };

  // 左滑：复制（预填今天的录入页）
  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 移除）
  const handleDelete = (tx: Transaction) => {
    Alert.alert(
      t('transactions.deleteTitle'),
      t('transactions.deleteMessage', { name: tx.narration || tx.payee || tx.date.slice(0, 10) }),
      [
        { text: t('common.cancel'), style: 'cancel' },
        { text: t('common.delete'), style: 'destructive', onPress: () => { deleteTransaction(tx.raw).catch(e => Alert.alert(t('common.error'), String(e))); } },
      ],
    );
  };

  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')} />

      {/* 方向筛选 + 高级筛选入口 */}
      <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}
            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={
          <Card title={t('transactions.noMatchTitle')}>
            <Text style={[theme.typography.body, { color: theme.colors.fgSecondary }]}>
              {allTransactions.length === 0 ? t('transactions.noMatchEmpty') : t('transactions.noMatchFiltered')}
            </Text>
          </Card>
        }
        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 },
});
