import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';

import '../../../core/l10n/app_localizations.dart';
import '../../../core/theme/app_colors.dart';
import '../../../providers/asset_provider.dart';
import '../../../providers/futures_provider.dart' show activeBottomTabProvider;

/// 资产页锁仓账户子 Tab 索引
const int kAssetStakingSubTabIndex = 5;

/// IDO 预售页「我的团队 / 锁仓总量」入口卡片（对齐 Web ido-overview）
class IdoOverviewCards extends ConsumerWidget {
  const IdoOverviewCards({
    super.key,
    required this.teamNum,
    required this.lockedTotal,
    this.loading = false,
  });

  final int teamNum;
  final String lockedTotal;
  final bool loading;

  static String _fmtAmount(String value, {int maxFrac = 8}) {
    final parsed = double.tryParse(value);
    if (parsed == null || !parsed.isFinite) {
      return '0';
    }
    if (parsed == 0) {
      return '0';
    }
    final pattern = maxFrac > 0 ? '#,##0.${'#' * maxFrac}' : '#,##0';
    return NumberFormat(pattern, 'en_US').format(parsed);
  }

  void _goToStakingAccount(BuildContext context, WidgetRef ref) {
    ref.read(currentAssetSubTabProvider.notifier).state =
        kAssetStakingSubTabIndex;
    ref.read(activeBottomTabProvider.notifier).state = kAssetStakingSubTabIndex;
    context.go('/asset?tab=staking');
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final l10n = AppLocalizations.of(context)!;
    final isDark = Theme.of(context).brightness == Brightness.dark;
    final primary =
        isDark ? Colors.white : Theme.of(context).colorScheme.onSurface;
    final labelColor = primary.withAlpha(140);
    final cardBg = primary.withAlpha(10);
    final cardBorder = primary.withAlpha(26);

    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),
      child: IntrinsicHeight(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Expanded(
              child: _OverviewCard(
                label: l10n.financeMyTeam,
                value: loading ? '—' : _fmtAmount('$teamNum', maxFrac: 0),
                labelColor: labelColor,
                valueColor: primary,
                backgroundColor: cardBg,
                borderColor: cardBorder,
                onTap: () => context.push('/finance/team'),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _OverviewCard(
                label: l10n.assetsStakingTotal,
                value: loading ? '—' : _fmtAmount(lockedTotal, maxFrac: 2),
                labelColor: labelColor,
                valueColor: primary,
                backgroundColor: cardBg,
                borderColor: cardBorder,
                onTap: () => _goToStakingAccount(context, ref),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _OverviewCard extends StatelessWidget {
  const _OverviewCard({
    required this.label,
    required this.value,
    required this.labelColor,
    required this.valueColor,
    required this.backgroundColor,
    required this.borderColor,
    required this.onTap,
  });

  final String label;
  final String value;
  final Color labelColor;
  final Color valueColor;
  final Color backgroundColor;
  final Color borderColor;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return Material(
      color: backgroundColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
        side: BorderSide(color: borderColor),
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(16),
        splashColor: AppColors.brand.withAlpha(40),
        highlightColor: AppColors.brand.withAlpha(20),
        child: Padding(
          padding: const EdgeInsets.fromLTRB(20, 20, 20, 22),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Flexible(
                    child: Text(
                      label,
                      style: TextStyle(color: labelColor, fontSize: 14),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Text(
                    ' >',
                    style: TextStyle(
                      color: labelColor.withAlpha(180),
                      fontSize: 13,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              SizedBox(
                height: 26,
                width: double.infinity,
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: FittedBox(
                    fit: BoxFit.scaleDown,
                    alignment: Alignment.centerLeft,
                    child: Text(
                      value,
                      maxLines: 1,
                      style: TextStyle(
                        color: valueColor,
                        fontSize: 22,
                        fontWeight: FontWeight.w600,
                        height: 1.1,
                        fontFeatures: const [FontFeature.tabularFigures()],
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
