import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/constants/app_colors.dart';
import '../../../core/utils/format_utils.dart';
import '../../providers/user_providers.dart';
import '../../providers/mining_providers.dart';
import 'widgets/asset_card.dart';
import 'widgets/price_card.dart';
import 'widgets/quick_actions.dart';

class HomePage extends ConsumerWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final user = ref.watch(userNotifierProvider);
    final accountSequence = user.accountSequence ?? '';

    return Scaffold(
      appBar: AppBar(
        title: const Text('榴莲挖矿'),
        backgroundColor: AppColors.primary,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.notifications_outlined),
            onPressed: () {},
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          ref.invalidate(shareAccountProvider(accountSequence));
          ref.invalidate(globalStateProvider);
        },
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 资产卡片
              AssetCard(accountSequence: accountSequence),

              const SizedBox(height: 16),

              // 当前价格
              const PriceCard(),

              const SizedBox(height: 24),

              // 快捷操作
              const Text(
                '快捷操作',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 12),
              const QuickActions(),

              const SizedBox(height: 24),

              // 全网数据
              const Text(
                '全网数据',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 12),
              _buildGlobalStats(ref),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildGlobalStats(WidgetRef ref) {
    final globalState = ref.watch(globalStateProvider);

    return globalState.when(
      data: (state) {
        if (state == null) return const SizedBox.shrink();
        return Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                _buildStatRow('全网算力', formatCompact(state.networkContribution)),
                const Divider(),
                _buildStatRow('已分配', formatCompact(state.totalDistributed)),
                const Divider(),
                _buildStatRow('已销毁', formatCompact(state.totalBurned)),
                const Divider(),
                _buildStatRow('流通池', formatCompact(state.circulationPool)),
              ],
            ),
          ),
        );
      },
      loading: () => const Card(
        child: Padding(
          padding: EdgeInsets.all(32),
          child: Center(child: CircularProgressIndicator()),
        ),
      ),
      error: (_, __) => const Card(
        child: Padding(
          padding: EdgeInsets.all(32),
          child: Center(child: Text('加载失败')),
        ),
      ),
    );
  }

  Widget _buildStatRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(color: AppColors.textSecondary)),
          Text(
            value,
            style: const TextStyle(fontWeight: FontWeight.w500),
          ),
        ],
      ),
    );
  }
}
