/**
 * 周期性账单管理页面。
 *
 * 功能：周期账单列表(频率/下次日期/资金流向/金额) + 添加/编辑/删除。
 * P5：套 ManagementScreen 模板；卡片底部保留显式编辑/删除按钮
 * （调 handlers.openEdit/confirmDelete），不用长按。
 */
import React from 'react';
import { Alert, 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 { toDateString } from '../../domain/core/decimal';
import type { RecurringTransaction } from '../../domain/finance/recurring';

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

  const recurringTransactions = useMetadataStore(s => s.recurringTransactions);
  const addRecurring = useMetadataStore(s => s.addRecurringTransaction);
  const updateRecurring = useMetadataStore(s => s.updateRecurringTransaction);
  const removeRecurring = useMetadataStore(s => s.removeRecurringTransaction);

  // 用本地时区格式化，避免 toISOString 的 UTC 偏移导致负时区日期错位
  const today = toDateString(new Date());

  return (
    <ManagementScreen<RecurringTransaction>
      title={t('recurring.title')}
      items={recurringTransactions}
      keyExtractor={item => item.id}
      addLabel={t('recurring.add')}
      emptyText={t('recurring.empty')}
      renderItem={(item, { openEdit, confirmDelete }) => {
        const amount = item.draft.postings[1]?.amount || '0.00';
        const fromAcc = item.draft.postings[0]?.account || '';
        const toAcc = item.draft.postings[1]?.account || '';

        return (
          <Card title={item.name}>
            <View style={styles.infoRow}>
              <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('recurring.frequency')}</Text>
              <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary }]}>
                {item.frequency === 'monthly' ? t('recurring.freqMonthly') : item.frequency === 'weekly' ? t('recurring.freqWeekly') : item.frequency === 'yearly' ? t('recurring.freqYearly') : t('recurring.freqDaily')}
              </Text>
            </View>
            <View style={styles.infoRow}>
              <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('recurring.nextDue')}</Text>
              <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary }]}>{item.nextDueDate}</Text>
            </View>
            <View style={styles.infoRow}>
              <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('recurring.flow')}</Text>
              <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary }]}>
                {fromAcc.split(':').pop()} ➔ {toAcc.split(':').pop()}
              </Text>
            </View>
            <View style={styles.infoRow}>
              <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('recurring.perAmount')}</Text>
              <Text style={[theme.typography.body, { color: theme.colors.financial.expense, fontWeight: '700' }]}>{amount} CNY</Text>
            </View>

            {/* 显式编辑/删除按钮（本页不用长按手势，交互更显式） */}
            <View style={styles.cardActions}>
              <Pressable
                onPress={openEdit}
                style={[styles.actionBtn, { borderColor: theme.colors.border, marginRight: 8 }]}
              >
                <Ionicons name="create-outline" size={14} color={theme.colors.accent} />
                <Text style={[theme.typography.caption, { color: theme.colors.accent, marginLeft: 4 }]}>
                  {t('recurring.edit')}
                </Text>
              </Pressable>
              <Pressable
                onPress={confirmDelete}
                style={[styles.actionBtn, { borderColor: theme.colors.border }]}
              >
                <Ionicons name="trash-outline" size={14} color={theme.colors.error} />
                <Text style={[theme.typography.caption, { color: theme.colors.error, marginLeft: 4 }]}>
                  {t('recurring.delete')}
                </Text>
              </Pressable>
            </View>
          </Card>
        );
      }}
      formTitle={editing => (editing ? t('recurring.editTitle') : t('recurring.addTitle'))}
      formFields={editing => [
        { key: 'name', label: t('recurring.fieldName'), placeholder: t('recurring.fieldNamePlaceholder'), defaultValue: editing?.name },
        { key: 'fromAccount', label: t('recurring.fieldFromAccount'), placeholder: '例如: Assets:支付宝余额', defaultValue: editing?.draft.postings[0]?.account?.replace(/^-/, '') || 'Assets:支付宝余额' },
        { key: 'toAccount', label: t('recurring.fieldToAccount'), placeholder: '例如: Expenses:Shopping', defaultValue: editing?.draft.postings[1]?.account || 'Expenses:Shopping' },
        { key: 'amount', label: t('recurring.fieldAmount'), placeholder: '例如: 6.00', defaultValue: editing?.draft.postings[1]?.amount },
        { key: 'frequency', label: t('recurring.fieldFrequency'), placeholder: 'monthly', defaultValue: editing?.frequency || 'monthly' },
        { key: 'nextDueDate', label: t('recurring.fieldNextDue'), placeholder: 'YYYY-MM-DD', defaultValue: editing?.nextDueDate || today },
      ]}
      onSubmit={(values, editing) => {
        const nameVal = values.name?.trim();
        const fromAccount = values.fromAccount?.trim();
        const toAccount = values.toAccount?.trim();
        const amountVal = values.amount?.trim();
        const freq = (values.frequency?.trim() || 'monthly') as RecurringTransaction['frequency'];
        const dateVal = values.nextDueDate?.trim() || today;

        if (!nameVal || !fromAccount || !toAccount || !amountVal) {
          Alert.alert(t('recurring.inputError'), t('recurring.inputErrorDesc'));
          return false;
        }

        const draft = {
          date: dateVal,
          narration: nameVal,
          postings: [
            { account: fromAccount, amount: `-${amountVal}`, currency: 'CNY' },
            { account: toAccount, amount: amountVal, currency: 'CNY' },
          ],
        };

        if (editing) {
          updateRecurring(editing.id, {
            name: nameVal,
            draft,
            frequency: freq,
            nextDueDate: dateVal,
          });
          Alert.alert(t('recurring.editSuccess'), t('recurring.editSuccessDesc', { name: nameVal }));
        } else {
          addRecurring({
            id: 'rec_' + generateId(),
            name: nameVal,
            draft,
            frequency: freq,
            interval: 1,
            nextDueDate: dateVal,
            enabled: true,
          });
          Alert.alert(t('recurring.addSuccess'), t('recurring.addSuccessDesc', { name: nameVal }));
        }
        // 弹窗关闭由模板接管（返回 true）
        return true;
      }}
      onDelete={item => removeRecurring(item.id)}
      deleteConfirmText={item => t('recurring.deleteConfirm', { name: item.name })}
      deleteConfirmTitle={t('recurring.deleteTitle')}
    />
  );
}

const styles = StyleSheet.create({
  infoRow: { flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 4, alignItems: 'center' },
  cardActions: { flexDirection: 'row', justifyContent: 'flex-end', marginTop: 8 },
  actionBtn: { flexDirection: 'row', alignItems: 'center', borderWidth: 1, borderRadius: 4, paddingHorizontal: 8, paddingVertical: 4 },
});
