import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/di/injection.dart';
import '../../../data/datasources/remote/referral_remote_datasource.dart';
import '../../widgets/team_tree_widget.dart';
import '../../providers/user_providers.dart';
import '../../providers/profile_providers.dart';
import '../../../data/models/capability_model.dart';

class TeamPage extends ConsumerStatefulWidget {
  const TeamPage({super.key});

  @override
  ConsumerState<TeamPage> createState() => _TeamPageState();
}

class _TeamPageState extends ConsumerState<TeamPage> {
  // 设计色彩
  static const Color _orange = Color(0xFFFF6B00);
  static const Color _darkText = Color(0xFF1F2937);
  static const Color _grayText = Color(0xFF6B7280);
  static const Color _bgGray = Color(0xFFF3F4F6);

  TeamTreeNode? _rootNode;
  bool _isLoading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadRootNode();
  }

  Future<void> _loadRootNode() async {
    final capabilities = ref.read(capabilitiesProvider).valueOrNull ?? CapabilityMap.defaultAll();
    if (!capabilities.viewTeamEnabled) {
      setState(() {
        _isLoading = false;
        _error = '您的查看团队功能已被限制';
      });
      return;
    }

    final user = ref.read(userNotifierProvider);
    final stats = ref.read(userStatsProvider).valueOrNull;

    if (user.accountSequence == null) {
      setState(() {
        _isLoading = false;
        _error = '用户信息未加载';
      });
      return;
    }

    try {
      final dataSource = getIt<ReferralRemoteDataSource>();
      final teamInfo = await dataSource.getTeamInfo(
        accountSequence: user.accountSequence!,
      );

      setState(() {
        _rootNode = TeamTreeNode.createRoot(
          accountSequence: user.accountSequence!,
          personalPlantingCount: teamInfo.personalPlantingCount,
          teamPlantingCount: teamInfo.teamPlantingCount,
          directReferralCount: teamInfo.directReferralCount,
        );
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _error = e.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _bgGray,
      appBar: AppBar(
        title: const Text(
          '我的同伴',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: _darkText,
          ),
        ),
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
        iconTheme: const IconThemeData(color: _darkText),
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(_orange),
        ),
      );
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              '加载失败',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            Text(
              _error!,
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[500],
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _isLoading = true;
                  _error = null;
                });
                _loadRootNode();
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: _orange,
                foregroundColor: Colors.white,
              ),
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_rootNode == null) {
      return const Center(
        child: Text('暂无数据'),
      );
    }

    return Column(
      children: [
        // 统计信息卡片
        _buildStatsCard(),
        // 说明文字
        _buildInstructions(),
        // 团队树
        Expanded(
          child: Container(
            margin: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: TeamTreeWidget(
                rootNode: _rootNode!,
                referralDataSource: getIt<ReferralRemoteDataSource>(),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildStatsCard() {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildStatItem(
            '本人参与',
            '${_rootNode?.personalPlantingCount ?? 0} 棵',
            Icons.eco,
          ),
          _buildDivider(),
          _buildStatItem(
            '同伴参与',
            '${_rootNode?.teamPlantingCount ?? 0} 棵',
            Icons.groups,
          ),
          _buildDivider(),
          _buildStatItem(
            '引荐人数',
            '${_rootNode?.directReferralCount ?? 0} 人',
            Icons.person_add,
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(
          icon,
          color: _orange,
          size: 24,
        ),
        const SizedBox(height: 8),
        Text(
          value,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: _darkText,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: _grayText,
          ),
        ),
      ],
    );
  }

  Widget _buildDivider() {
    return Container(
      width: 1,
      height: 50,
      color: _bgGray,
    );
  }

  Widget _buildInstructions() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: _orange.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Icon(
            Icons.info_outline,
            color: _orange,
            size: 18,
          ),
          const SizedBox(width: 8),
          const Expanded(
            child: Text(
              '点击节点展开/收起下级成员，长按查看详情',
              style: TextStyle(
                fontSize: 12,
                color: _grayText,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
