import React, { useState } from 'react';
import { Alert, FlatList, Pressable, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useTheme } from '../../theme';
import { useLedgerStore } from '../../store/ledgerStore';
import { useT } from '../../i18n';
import { Card } from '../../components/ui/Card';
import { AccountCreateModal } from '../../components/account/AccountCreateModal';
import { FormModal } from '../../components/form/FormModal';
import { ScreenHeader } from '../../components/layout/ScreenHeader';
import { toDateString } from '../../domain/core/decimal';
import { computeAccountBalances } from '../../domain/core/ledger';
import { SegmentedControl } from '../../components/ui/SegmentedControl';
import { EmptyState } from '../../components/ui/EmptyState';
import { useToast } from '../../components/ui/Toast';

type TabType = 'assets' | 'liabilities' | 'expenses' | 'income';

export default function AccountScreen() {
  const { theme } = useTheme();
  const t = useT();
  const { showToast } = useToast();

  const ledger = useLedgerStore(s => s.ledger);
  const autoOpenAccounts = useLedgerStore(s => s.autoOpenAccounts);
  const autoCloseAccount = useLedgerStore(s => s.autoCloseAccount);
  const adjustAccountBalance = useLedgerStore(s => s.adjustAccountBalance);

  const [tab, setTab] = useState<TabType>('assets');
  const [isAdding, setIsAdding] = useState(false);
  const [adjustingAccount, setAdjustingAccount] = useState<string | null>(null);

  const accounts = Array.from(ledger?.accounts.keys() || []).sort();

  // 计算每个账户的余额（包含 balance 断言）
  const balances = ledger ? computeAccountBalances(ledger) : new Map<string, string>();

  // 根据当前选择的 Tab 过滤账户
  const prefix =
    tab === 'assets'
      ? 'Assets:'
      : tab === 'liabilities'
      ? 'Liabilities:'
      : tab === 'expenses'
      ? 'Expenses:'
      : 'Income:';

  const filteredAccounts = accounts.filter(a => a.startsWith(prefix));

  const handleCloseAccount = (accountName: string) => {
    Alert.alert(
      t('account.confirmClose'),
      t('account.confirmCloseDesc', { name: accountName }),
      [
        { text: t('common.cancel'), style: 'cancel' },
        {
          text: t('account.btnConfirmClose'),
          style: 'destructive',
          onPress: async () => {
            try {
              await autoCloseAccount(accountName);
              showToast(t('account.closeSuccessDesc'), 'success');
            } catch (e) {
              Alert.alert(t('account.closeFail'), e instanceof Error ? e.message : String(e));
            }
          },
        },
      ]
    );
  };

  const handleAddAccount = async (values: Record<string, string>) => {
    const typeVal = values.type?.trim();
    const nameVal = values.name?.trim();

    if (!typeVal || !nameVal) {
      Alert.alert(t('account.addFail'), t('account.addFailEmpty'));
      return;
    }

    // 拼接成 Beancount 账户名并清洗特殊字符
    const rawAccount = `${typeVal}:${nameVal}`;
    let sanitized = rawAccount.replace(/：/g, ':');
    sanitized = sanitized
      .split(':')
      .map((seg, idx) => {
        if (idx === 0) return seg; // 保留顶级前缀如 Assets
        // 将中英文括号和中括号转换为 - 连字符
        let cleaned = seg.replace(/[()（）[\]]/g, '-');
        cleaned = cleaned.replace(/-+/g, '-');
        cleaned = cleaned.replace(/^-|-$/g, '');
        cleaned = cleaned.replace(/[^\w\u4e00-\u9fa5-]/g, '');
        return cleaned;
      })
      .join(':');

    const rootType = sanitized.split(':')[0];
    const validRoots = ['Assets', 'Liabilities', 'Income', 'Expenses', 'Equity'];
    if (!validRoots.includes(rootType)) {
      Alert.alert(t('account.addFail'), t('account.invalidRootAccount'));
      return;
    }

    try {
      await autoOpenAccounts([sanitized]);
      setIsAdding(false);
      showToast(t('account.openSuccessDesc', { name: sanitized }), 'success');
    } catch (e) {
      Alert.alert(t('account.openFail'), e instanceof Error ? e.message : String(e));
    }
  };

  const handleConfirmAdjust = async (values: Record<string, string>) => {
    if (!adjustingAccount) return;
    const balanceVal = values.balance?.trim();
    const dateVal = values.date?.trim() || toDateString(new Date());

    if (!balanceVal) {
      Alert.alert(t('account.adjustFail'), t('account.adjustFailEmpty'));
      return;
    }

    try {
      await adjustAccountBalance(adjustingAccount, balanceVal, dateVal);
      setAdjustingAccount(null);
      showToast(t('account.adjustSuccessDesc', { name: adjustingAccount, balance: balanceVal, currency: 'CNY' }), 'success');
    } catch (e) {
      Alert.alert(t('account.adjustFail'), e instanceof Error ? e.message : String(e));
    }
  };

  const tabs: { key: TabType; label: string }[] = [
    { key: 'assets', label: t('account.tabAssets') },
    { key: 'liabilities', label: t('account.tabLiabilities') },
    { key: 'expenses', label: t('account.tabExpenses') },
    { key: 'income', label: t('account.tabIncome') },
  ];

  return (
    <SafeAreaView style={[styles.page, { backgroundColor: theme.colors.bgPrimary }]} edges={['top', 'bottom']}>
      <ScreenHeader title={t('account.title')} />

      {/* Tab 选项卡（统一分段选择器） */}
      <SegmentedControl
        options={tabs}
        value={tab}
        onChange={key => setTab(key as TabType)}
      />

      {/* 账户列表 */}
      <FlatList
        data={filteredAccounts}
        keyExtractor={account => account}
        renderItem={({ item: account }) => {
          const shortName = account.slice(prefix.length);
          const rootType = account.split(':')[0] as 'Assets' | 'Liabilities' | 'Expenses' | 'Income' | 'Equity';
          const localizedRoot = t(`account.rootLabels.${rootType}`);
          const balance = balances.get(account) ?? '0.00';
          const currency = ledger?.accounts.get(account)?.currencies[0] || 'CNY';

          return (
            <Card title={shortName}>
              <View style={styles.infoRow}>
                <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
                  {t('account.fullName')}
                </Text>
                <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary }]}>
                  {account} {localizedRoot ? `(${localizedRoot})` : ''}
                </Text>
              </View>
              <View style={styles.infoRow}>
                <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
                  {t('account.currentBalance')}
                </Text>
                <Text
                  style={[
                    theme.typography.body,
                    { color: balance.startsWith('-') ? theme.colors.error : theme.colors.info, fontWeight: '700' },
                  ]}
                >
                  {balance} {currency}
                </Text>
              </View>

              <View style={styles.cardActions}>
                <Pressable
                  onPress={() => setAdjustingAccount(account)}
                  style={[styles.actionBtn, { borderColor: theme.colors.border, borderRadius: theme.radii.sm, marginRight: 8 }]}
                >
                  <Ionicons name="create-outline" size={14} color={theme.colors.accent} />
                  <Text style={[theme.typography.caption, { color: theme.colors.accent, marginLeft: 4 }]}>
                    {t('account.adjustBalance')}
                  </Text>
                </Pressable>
                <Pressable
                  onPress={() => handleCloseAccount(account)}
                  style={[styles.closeBtn, { borderColor: theme.colors.border, borderRadius: theme.radii.sm }]}
                >
                  <Ionicons name="close-circle-outline" size={14} color={theme.colors.error} />
                  <Text style={[theme.typography.caption, { color: theme.colors.error, marginLeft: 4 }]}>
                    {t('account.closeAccount')}
                  </Text>
                </Pressable>
              </View>
            </Card>
          );
        }}
        ListHeaderComponent={
          <Pressable onPress={() => setIsAdding(true)} style={styles.addBtn}>
            <Ionicons name="add-circle" size={20} color={theme.colors.accent} />
            <Text style={[theme.typography.body, { color: theme.colors.accent, marginLeft: 6 }]}>
              {t('account.addNew')}
            </Text>
          </Pressable>
        }
        ListEmptyComponent={
          <EmptyState icon="wallet-outline" title={t('account.empty')} />
        }
        contentContainerStyle={[styles.content, { gap: theme.spacing.md }]}
      />

      {/* 新开户对话框 */}
      <AccountCreateModal
        visible={isAdding}
        defaultType={tab === 'assets' ? 'Assets' : tab === 'liabilities' ? 'Liabilities' : tab === 'expenses' ? 'Expenses' : 'Income'}
        onConfirm={handleAddAccount}
        onCancel={() => setIsAdding(false)}
      />

      {/* 调整余额对话框 */}
      <FormModal
        visible={adjustingAccount !== null}
        title={t('account.adjustModalTitle')}
        fields={[
          {
            key: 'balance',
            label: t('account.fieldBalance'),
            placeholder: t('account.fieldBalancePlaceholder'),
            defaultValue: adjustingAccount ? (balances.get(adjustingAccount) ?? '0.00') : '0.00',
          },
          {
            key: 'date',
            label: t('account.fieldDate'),
            placeholder: 'YYYY-MM-DD',
            defaultValue: toDateString(new Date()),
          },
        ]}
        onConfirm={handleConfirmAdjust}
        onCancel={() => setAdjustingAccount(null)}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  page: { flex: 1 },
  content: { padding: 16 },
  addBtn: { flexDirection: 'row', alignItems: 'center', marginBottom: 8 },
  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, paddingHorizontal: 8, paddingVertical: 4 },
  closeBtn: { flexDirection: 'row', alignItems: 'center', borderWidth: 1, paddingHorizontal: 8, paddingVertical: 4 },
});
