/**
 * 信用卡管理页面（plan.md「1.1 credit-card/index」+ 决策 1 双轨制）。
 *
 * 功能：信用卡列表(银行/尾号/账单日/还款日/额度/账单盒) + 添加/编辑/删除。
 * linkedAccount 映射到 Beancount 的 Liabilities 账户。
 * P5：套 ManagementScreen 模板，富 renderItem 直套。
 */
import React, { useMemo, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { useTheme } from '../../theme';
import { useMetadataStore, generateId } from '../../store/metadataStore';
import { useLedgerStore } from '../../store/ledgerStore';
import { useT } from '../../i18n';
import { Card } from '../../components/ui/Card';
import { ManagementScreen } from '../../components/layout/ManagementScreen';
import { AccountCreateModal } from '../../components/account/AccountCreateModal';
import { Touchable } from '../../components/ui/Touchable';
import type { CreditCard } from '../../domain/finance/creditCards';
import { calculateBillingPeriod, calculateStatementAmount, calculateAvailableCredit } from '../../domain/finance/creditCards';

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

  const creditCards = useMetadataStore(s => s.creditCards);
  const addCreditCard = useMetadataStore(s => s.addCreditCard);
  const updateCreditCard = useMetadataStore(s => s.updateCreditCard);
  const removeCreditCard = useMetadataStore(s => s.removeCreditCard);

  const ledger = useLedgerStore(s => s.ledger);
  const autoOpenAccounts = useLedgerStore(s => s.autoOpenAccounts);
  const transactions = useMemo(() => ledger?.transactions ?? [], [ledger?.transactions]);

  const [isQuickAddingAccount, setIsQuickAddingAccount] = useState(false);

  /** 过滤出所有以 Liabilities 开头的信用负债账户。 */
  const liabilityAccounts = useMemo(() => {
    if (!ledger?.accounts) return [];
    const accountNames = Array.from(ledger.accounts.keys());
    return accountNames.filter((name: string) => name.startsWith('Liabilities'));
  }, [ledger?.accounts]);

  const liabilityOptions = useMemo(() => {
    return liabilityAccounts.map((name: string) => ({
      label: name.replace(/^Liabilities:/, ''),
      value: name,
    }));
  }, [liabilityAccounts]);

  /** 预计算所有账户余额 Map（避免在渲染循环中重复遍历）。 */
  const accountBalances = useMemo(() => {
    const map = new Map<string, string>();
    for (const tx of transactions) {
      for (const p of tx.postings) {
        if (p.account && p.amount) {
          const prev = parseFloat(map.get(p.account) ?? '0');
          map.set(p.account, (prev + parseFloat(p.amount)).toFixed(2));
        }
      }
    }
    return map;
  }, [transactions]);

  const getAccountBalance = (account: string): string => accountBalances.get(account) ?? '0.00';

  const handleQuickAddAccount = (values: Record<string, string>) => {
    const type = values.type || 'Liabilities';
    const name = values.name?.trim() || 'CreditCard';
    const fullAccountName = `${type}:${name}`;
    autoOpenAccounts([fullAccountName]);
    setIsQuickAddingAccount(false);
  };

  return (
    <>
      <ManagementScreen<CreditCard>
        title={t('creditCard.title')}
        items={creditCards}
        keyExtractor={card => card.id}
        addLabel={t('creditCard.add')}
        emptyText={t('creditCard.empty')}
        renderItem={(card, { openEdit, confirmDelete }) => {
          const period = calculateBillingPeriod(card, new Date());
          const statementAmount = calculateStatementAmount(transactions, card, period);
          const currentBalance = getAccountBalance(card.linkedAccount);
          const availableCredit = calculateAvailableCredit(card, currentBalance);
          return (
            <Card title={card.name} onPress={openEdit} onLongPress={confirmDelete}>
              <View style={styles.infoRow}>
                <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('creditCard.labelBank')}</Text>
                <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary }]}>{card.bankName} ({card.lastFour})</Text>
              </View>
              <View style={styles.infoRow}>
                <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('creditCard.labelBillingDay')}</Text>
                <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary }]}>{card.billingDay} {t('creditCard.daySuffix')}</Text>
              </View>
              <View style={styles.infoRow}>
                <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('creditCard.labelPaymentDay')}</Text>
                <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary }]}>{card.paymentDay} {t('creditCard.daySuffix')}</Text>
              </View>
              <View style={styles.infoRow}>
                <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('creditCard.labelLimit')}</Text>
                <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary }]}>{card.creditLimit} {card.currency}</Text>
              </View>
              <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginTop: 4 }]}>{card.linkedAccount}</Text>

              {/* 账单周期与应还 */}
              <View style={[styles.billingBox, { borderColor: theme.colors.divider }]}>
                <View style={styles.infoRow}>
                  <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('creditCard.billingPeriod')}</Text>
                  <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary }]}>{period.periodStart} ~ {period.periodEnd}</Text>
                </View>
                <View style={styles.infoRow}>
                  <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('creditCard.dueDate')}</Text>
                  <Text style={[theme.typography.bodySmall, { color: theme.colors.error }]}>{period.dueDate}</Text>
                </View>
                <View style={styles.infoRow}>
                  <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('creditCard.statementAmount')}</Text>
                  <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary, fontWeight: '700' }]}>{statementAmount} {card.currency}</Text>
                </View>
                <View style={styles.infoRow}>
                  <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>{t('creditCard.availableCredit')}</Text>
                  <Text style={[theme.typography.bodySmall, { color: theme.colors.accent }]}>{availableCredit} {card.currency}</Text>
                </View>
              </View>
            </Card>
          );
        }}
        formTitle={editing => (editing ? t('creditCard.editTitle') : t('creditCard.add'))}
        onValuesChange={(changedKey: string, newValue: string, currentValues: Record<string, string>) => {
          if (changedKey === 'linkedAccount' && newValue) {
            const shortName = newValue.includes(':') ? newValue.slice(newValue.lastIndexOf(':') + 1) : newValue;
            const updates: Record<string, string> = {};
            if (shortName) {
              updates.name = shortName;
              if (shortName.includes('招商') || shortName.toUpperCase().includes('CMB')) updates.bankName = '招商银行';
              else if (shortName.includes('支付宝') || shortName.includes('花呗')) updates.bankName = '支付宝';
              else if (shortName.includes('微信') || shortName.includes('微粒贷')) updates.bankName = '微信';
              else if (shortName.includes('建设') || shortName.toUpperCase().includes('CCB')) updates.bankName = '建设银行';
              else if (shortName.includes('工商') || shortName.toUpperCase().includes('ICBC')) updates.bankName = '工商银行';
              else if (shortName.includes('中国银行') || shortName.toUpperCase().includes('BOC')) updates.bankName = '中国银行';
              else if (shortName.includes('农业') || shortName.toUpperCase().includes('ABC')) updates.bankName = '农业银行';
              else if (shortName.includes('交通') || shortName.toUpperCase().includes('BOCOM')) updates.bankName = '交通银行';
              else if (!currentValues.bankName) updates.bankName = shortName;
            }
            return updates;
          }
        }}
        formFields={editing => [
          // Row 1: linkedAccount (1.5) + name (1.0)
          liabilityOptions.length > 0
            ? {
                key: 'linkedAccount',
                label: t('creditCard.fieldLinkedAccount'),
                type: 'dropdown',
                options: liabilityOptions,
                placeholder: '请选择关联信用账户',
                defaultValue: editing?.linkedAccount ?? '',
                flex: 1.5,
                row: 1,
              }
            : {
                key: 'linkedAccount',
                label: t('creditCard.fieldLinkedAccount'),
                placeholder: 'Liabilities:CreditCard:CMB',
                defaultValue: editing?.linkedAccount ?? '',
                flex: 1.5,
                row: 1,
              },
          { key: 'name', label: t('creditCard.fieldName'), placeholder: '招行信用卡', defaultValue: editing?.name, flex: 1.0, row: 1 },

          // Row 2: bankName (1.0) + lastFour (1.0) + currency (1.0)
          { key: 'bankName', label: t('creditCard.fieldBank'), placeholder: '招商银行', defaultValue: editing?.bankName, flex: 1.0, row: 2 },
          { key: 'lastFour', label: t('creditCard.fieldLastFour'), placeholder: '1234', defaultValue: editing?.lastFour, keyboardType: 'numeric', flex: 1.0, row: 2 },
          { key: 'currency', label: t('creditCard.fieldCurrency'), placeholder: 'CNY', defaultValue: editing?.currency ?? 'CNY', flex: 1.0, row: 2 },

          // Row 3: billingDay (1.0) + paymentDay (1.0) + creditLimit (1.2)
          { key: 'billingDay', label: t('creditCard.fieldBillingDay'), placeholder: '5', defaultValue: editing ? String(editing.billingDay) : '5', keyboardType: 'numeric', flex: 1.0, row: 3 },
          { key: 'paymentDay', label: t('creditCard.fieldPaymentDay'), placeholder: '25', defaultValue: editing ? String(editing.paymentDay) : '25', keyboardType: 'numeric', flex: 1.0, row: 3 },
          { key: 'creditLimit', label: t('creditCard.fieldLimit'), placeholder: '10000', defaultValue: editing?.creditLimit ?? '10000', keyboardType: 'decimal-pad', flex: 1.2, row: 3 },
        ]}
        formExtra={() => (
          <Touchable
            onPress={() => setIsQuickAddingAccount(true)}
            style={styles.quickAddBtn}
          >
            <Text style={[theme.typography.caption, { color: theme.colors.accent, fontWeight: '600' }]}>
              ＋ 快捷新建负债账户
            </Text>
          </Touchable>
        )}
        onSubmit={(values, editing) => {
          const card: Omit<CreditCard, 'id'> = {
            name: values.name?.trim() || t('creditCard.unnamed'),
            lastFour: values.lastFour?.trim() || '0000',
            bankName: values.bankName?.trim() || 'UNKNOWN',
            billingDay: parseInt(values.billingDay, 10) || 1,
            paymentDay: parseInt(values.paymentDay, 10) || 1,
            creditLimit: values.creditLimit?.trim() || '0',
            currency: values.currency?.trim() || 'CNY',
            linkedAccount: values.linkedAccount?.trim() || 'Liabilities:CreditCard',
          };
          if (editing) {
            updateCreditCard(editing.id, card);
          } else {
            addCreditCard({ ...card, id: generateId('cc') });
          }
          return true;
        }}
        onDelete={card => removeCreditCard(card.id)}
        deleteConfirmText={card => t('creditCard.deleteConfirm', { name: card.name })}
        deleteConfirmTitle={t('creditCard.deleteTitle')}
        footer={
          <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, textAlign: 'center' }]}>
            {t('common.clickEditLongDelete')}
          </Text>
        }
      />

      {/* 快捷新建负债账户弹窗 */}
      <AccountCreateModal
        visible={isQuickAddingAccount}
        defaultType="Liabilities"
        onConfirm={handleQuickAddAccount}
        onCancel={() => setIsQuickAddingAccount(false)}
      />
    </>
  );
}

const styles = StyleSheet.create({
  infoRow: { flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 4 },
  billingBox: { marginTop: 8, padding: 8, borderRadius: 6, borderWidth: 1 },
  quickAddBtn: { paddingVertical: 6, alignItems: 'center', marginTop: 4 },
});
