/**
 * 首页（spec §7.1）：今日视角。
 * 问候 header → 净资产白卡（本月收支/预算剩余小字）→ 待办条 → 最近 5 条 → 月度趋势。
 * 账户树已下沉到「我的」页（/account）。
 */
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { FlatList, Pressable, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { useLedgerStore } from '../../store/ledgerStore';
import { useMetadataStore } from '../../store/metadataStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { Card } from '../../components/ui/Card';
import { TransactionCard } from '../../components/transaction/TransactionCard';
import { TodoStrip } from '../../components/stats/TodoStrip';
import { TrendLine } from '../../components/charts/TrendLine';
import { calculateNetWorth } from '../../domain/stats/netWorth';
import { groupByMonth } from '../../domain/stats/chartStats';
import { getDueRecurring, instantiateRecurring, calculateNextDueDate } from '../../domain/finance/recurring';
import { calculateBudgetProgress } from '../../domain/finance/budgets';
import { addDecimals, toDateString } from '../../domain/core/decimal';
import type { Transaction } from '../../domain/core/types';
import { EmptyState } from '../../components/ui/EmptyState';
import { useNumpadUiStore } from '../../store/numpadUiStore';

export default function HomeScreen() {
  const { theme } = useTheme();
  const t = useT();
  const router = useRouter();

  const ledger = useLedgerStore(s => s.ledger);
  const addTransaction = useLedgerStore(s => s.addTransaction);
  const recurringTransactions = useMetadataStore(s => s.recurringTransactions);
  const updateRecurringTransaction = useMetadataStore(s => s.updateRecurringTransaction);
  const budgets = useMetadataStore(s => s.budgets);
  const categories = useMetadataStore(s => s.categories);
  const locale = useSettingsStore(s => s.locale);

  const transactions = useMemo(() => ledger?.transactions ?? [], [ledger]);
  const netWorth = useMemo(() => calculateNetWorth(transactions), [transactions]);
  const monthlyData = useMemo(() => groupByMonth(transactions), [transactions]);
  const currentMonth = useMemo(() => monthlyData.length ? monthlyData[monthlyData.length - 1] : null, [monthlyData]);

  const todayStr = useMemo(() => toDateString(new Date()), []);
  const dueRecurring = useMemo(() => getDueRecurring(recurringTransactions, todayStr), [recurringTransactions, todayStr]);

  // 周期记账自动触发：启动时自动确认标记了 autoConfirm 的到期项
  const autoConfirmed = useRef(false);
  useEffect(() => {
    let isMounted = true;
    if (autoConfirmed.current) return;
    const autoDue = dueRecurring.filter(r => r.autoConfirm);
    if (autoDue.length === 0) return;
    autoConfirmed.current = true;
    (async () => {
      for (const rec of autoDue) {
        if (!isMounted) break;
        try {
          const draft = instantiateRecurring(rec);
          await addTransaction(draft);
          const nextDueDate = calculateNextDueDate(rec.frequency, rec.interval, rec.nextDueDate);
          updateRecurringTransaction(rec.id, { nextDueDate });
        } catch {
          // 静默失败，用户可在周期管理页手动处理
        }
      }
    })();
    return () => { isMounted = false; };
  }, [dueRecurring, addTransaction, updateRecurringTransaction]);

  // 月度预算剩余合计（无月度预算则不显示）
  const budgetRemaining = useMemo(() => {
    const monthlyBudgets = budgets.filter(b => b.period === 'monthly');
    if (monthlyBudgets.length === 0) return null;
    const remainings = monthlyBudgets.map(b => calculateBudgetProgress(b, transactions, todayStr).remaining);
    return remainings.reduce((a, b) => addDecimals([a, b]), '0');
  }, [budgets, transactions, todayStr]);

  // 最近 5 条（按日期+序号倒序）
  const recentTxs = useMemo(() =>
    transactions.map((tx, idx) => ({ tx, idx }))
      .sort((a, b) => b.tx.date.localeCompare(a.tx.date) || b.idx - a.idx)
      .slice(0, 5)
      .map(item => item.tx),
  [transactions]);

  // 分类匹配（TransactionCard 图标）
  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 hour = new Date().getHours();
  const greeting = hour < 12 ? t('home.greetingMorning') : hour < 18 ? t('home.greetingAfternoon') : t('home.greetingEvening');
  const localeTag = locale === 'zh' ? 'zh-CN' : 'en-US';
  const dateLine = new Date().toLocaleDateString(localeTag, { month: 'long', day: 'numeric', weekday: 'long' });

  // 千分位格式化金额
  const fmtAmount = (s: string) => {
    if (!s || s === '0') return '¥0.00';
    const num = parseFloat(s);
    if (isNaN(num)) return s;
    const formatted = num.toLocaleString(localeTag, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    return num >= 0 ? `¥${formatted}` : `-¥${Math.abs(num).toLocaleString(localeTag, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  };

  return (
    <SafeAreaView style={[styles.page, { backgroundColor: theme.colors.bgPrimary }]} edges={['top']}>
      <View style={styles.header}>
        <Text style={[theme.typography.h2, { color: theme.colors.fgPrimary }]}>{greeting}</Text>
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginTop: 2 }]}>{dateLine}</Text>
      </View>
      <FlatList
        data={recentTxs}
        keyExtractor={(tx) => tx.id}
        contentContainerStyle={[styles.content, { gap: theme.spacing.md }]}
        ListHeaderComponent={
          <View style={{ gap: theme.spacing.md }}>
            {/* 净资产白卡 */}
            <Card>
              <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('home.netWorthTitle')}</Text>
              <Text style={[theme.typography.display, { color: theme.colors.fgPrimary, marginVertical: 6, fontVariant: ['tabular-nums'] }]}>
                {fmtAmount(netWorth.netWorth)}
              </Text>
              <View style={[styles.heroFooter, { borderTopColor: theme.colors.divider }]}>
                <View style={styles.heroStat}>
                  <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('home.monthExpense')}</Text>
                  <Text style={[theme.typography.bodySmall, { color: theme.colors.financial.expense, fontWeight: '700', fontVariant: ['tabular-nums'] }]}>
                    -{fmtAmount(currentMonth?.expense.toString() ?? '0')}
                  </Text>
                </View>
                <View style={styles.heroStat}>
                  <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('home.monthIncome')}</Text>
                  <Text style={[theme.typography.bodySmall, { color: theme.colors.financial.income, fontWeight: '700', fontVariant: ['tabular-nums'] }]}>
                    +{fmtAmount(currentMonth?.income.toString() ?? '0')}
                  </Text>
                </View>
                {budgetRemaining !== null && (
                  <View style={styles.heroStat}>
                    <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('home.budgetRemaining')}</Text>
                    <Text style={[theme.typography.bodySmall, { color: theme.colors.accent, fontWeight: '700', fontVariant: ['tabular-nums'] }]}>
                      {fmtAmount(budgetRemaining)}
                    </Text>
                  </View>
                )}
              </View>
            </Card>

            <TodoStrip />

            {/* 月度趋势 */}
            {monthlyData.length > 0 && (
              <Card title={t('home.monthlyTrend')}>
                <TrendLine transactions={transactions} />
              </Card>
            )}

            {/* 最近交易标题 */}
            {recentTxs.length > 0 && (
              <Text style={[theme.typography.h3, { color: theme.colors.fgPrimary, fontWeight: '700' }]}>{t('home.recentTransactions')}</Text>
            )}
          </View>
        }
        renderItem={({ item: tx }) => (
          <TransactionCard key={tx.id} transaction={tx} categoryId={categoryIdFor(tx)} onPress={() => router.push(`/transaction/${tx.id}`)} />
        )}
        ListFooterComponent={
          <>
            {recentTxs.length > 0 && (
              <Pressable onPress={() => router.push('/(tabs)/transactions')} style={styles.viewAll} accessibilityRole="button" accessibilityLabel={t('home.viewAll')}>
                <Text style={[theme.typography.bodySmall, { color: theme.colors.accent, fontWeight: '700' }]}>{t('home.viewAll')} →</Text>
              </Pressable>
            )}
            {/* 无交易时的记账引导 */}
            {transactions.length === 0 && (
              <EmptyState
                icon="add-circle-outline"
                title={t('home.recentEmpty')}
                actionLabel={t('home.newTransaction')}
                onAction={() => useNumpadUiStore.getState().open()}
              />
            )}
          </>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  page: { flex: 1 },
  header: { paddingHorizontal: 16, paddingTop: 8, paddingBottom: 12 },
  content: { padding: 16, paddingBottom: 40 },
  heroFooter: { flexDirection: 'row', gap: 16, borderTopWidth: StyleSheet.hairlineWidth, paddingTop: 10, marginTop: 4 },
  heroStat: { gap: 2 },
  viewAll: { alignItems: 'center', paddingVertical: 6 },
});
