import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/referral_service.dart';
import '../../../../core/services/authorization_service.dart';

/// [2026-03-02] 团队预种页面（功能6）
///
/// 显示当前用户的团队预种统计：
/// - 个人预种份数、团队预种总量
/// - 直推成员预种明细（所有用户可见）
/// - 全部团队成员预种明细（仅市/省公司管理者可见，分页加载）
class TeamPrePlantingPage extends ConsumerStatefulWidget {
  const TeamPrePlantingPage({super.key});

  @override
  ConsumerState<TeamPrePlantingPage> createState() => _TeamPrePlantingPageState();
}

class _TeamPrePlantingPageState extends ConsumerState<TeamPrePlantingPage> {
  // 统计数据
  int _selfPrePlantingPortions = 0;
  int _teamPrePlantingPortions = 0;
  List<DirectPrePlantingInfo> _directReferrals = [];

  // 团队成员明细（分页）
  List<TeamMemberPrePlanting> _teamMembers = [];
  int _memberTotal = 0;
  bool _memberHasMore = false;
  int _memberOffset = 0;
  static const int _memberPageSize = 20;

  // 加载状态
  bool _isLoading = true;
  String? _errorMessage;
  bool _hasCompanyRole = false;
  bool _isLoadingMembers = false;

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

  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final referralService = ref.read(referralServiceProvider);
      final authorizationService = ref.read(authorizationServiceProvider);

      // 并行加载：团队预种统计 + 授权角色
      final results = await Future.wait([
        referralService.getTeamPrePlanting(),
        authorizationService.getMyAuthorizations(),
      ]);

      final teamPrePlanting = results[0] as TeamPrePlantingResponse;
      final authorizations = results[1] as List<AuthorizationResponse>;

      // 检查是否有市/省公司角色
      final hasRole = authorizations.any((auth) =>
          auth.status != AuthorizationStatus.revoked &&
          (auth.roleType == RoleType.authCityCompany ||
           auth.roleType == RoleType.cityCompany ||
           auth.roleType == RoleType.authProvinceCompany ||
           auth.roleType == RoleType.provinceCompany));

      if (mounted) {
        setState(() {
          _selfPrePlantingPortions = teamPrePlanting.selfPrePlantingPortions;
          _teamPrePlantingPortions = teamPrePlanting.teamPrePlantingPortions;
          _directReferrals = teamPrePlanting.directReferrals;
          _hasCompanyRole = hasRole;
          _isLoading = false;
        });

        // 如果有公司角色，加载团队成员明细
        if (hasRole) {
          _loadTeamMembers();
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载失败: $e';
        });
      }
    }
  }

  Future<void> _loadTeamMembers() async {
    if (_isLoadingMembers) return;
    setState(() => _isLoadingMembers = true);

    try {
      final referralService = ref.read(referralServiceProvider);
      final result = await referralService.getTeamPrePlantingMembers(
        limit: _memberPageSize,
        offset: _memberOffset,
      );

      if (mounted) {
        setState(() {
          _teamMembers.addAll(result.members);
          _memberTotal = result.total;
          _memberHasMore = result.hasMore;
          _isLoadingMembers = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoadingMembers = false);
      }
      debugPrint('加载团队成员预种明细失败: $e');
    }
  }

  Future<void> _loadMoreMembers() async {
    if (_isLoadingMembers || !_memberHasMore) return;
    _memberOffset += _memberPageSize;
    _loadTeamMembers();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFFFFF7E6), Color(0xFFEAE0C8)],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              _buildHeader(),
              Expanded(
                child: _isLoading
                    ? const Center(child: CircularProgressIndicator(color: Color(0xFFD4AF37)))
                    : _errorMessage != null
                        ? _buildError()
                        : RefreshIndicator(
                            color: const Color(0xFFD4AF37),
                            onRefresh: () async {
                              _teamMembers.clear();
                              _memberOffset = 0;
                              await _loadData();
                            },
                            child: _buildContent(),
                          ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => context.pop(),
            child: Container(
              width: 36,
              height: 36,
              decoration: BoxDecoration(
                color: Colors.white.withValues(alpha: 0.8),
                borderRadius: BorderRadius.circular(12),
              ),
              child: const Icon(Icons.arrow_back_ios_new, size: 16, color: Color(0xFF5D4037)),
            ),
          ),
          const Expanded(
            child: Text(
              '团队预种',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w700,
                fontFamily: 'Inter',
                color: Color(0xFF5D4037),
              ),
            ),
          ),
          const SizedBox(width: 36),
        ],
      ),
    );
  }

  Widget _buildError() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.error_outline, size: 48, color: Color(0xFF5D4037)),
          const SizedBox(height: 12),
          Text(
            _errorMessage ?? '加载失败',
            style: const TextStyle(fontSize: 14, color: Color(0xFF5D4037)),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: () {
              _teamMembers.clear();
              _memberOffset = 0;
              _loadData();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFFD4AF37),
              foregroundColor: Colors.white,
            ),
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildContent() {
    return ListView(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      children: [
        const SizedBox(height: 8),
        // 统计卡片
        _buildStatsCards(),
        const SizedBox(height: 20),
        // 直推预种明细
        _buildDirectReferralsSection(),
        const SizedBox(height: 20),
        // 团队成员预种明细（角色限制）
        _buildTeamMembersSection(),
        const SizedBox(height: 20),
      ],
    );
  }

  Widget _buildStatsCards() {
    return Row(
      children: [
        Expanded(
          child: _buildStatCard(
            '个人预种',
            '$_selfPrePlantingPortions',
            '份',
            const Color(0xFFD4AF37),
            Icons.person_outline,
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: _buildStatCard(
            '团队预种总量',
            '$_teamPrePlantingPortions',
            '份',
            const Color(0xFF2E7D32),
            Icons.groups_outlined,
          ),
        ),
      ],
    );
  }

  Widget _buildStatCard(String label, String value, String suffix, Color color, IconData icon) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: color.withValues(alpha: 0.1),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(icon, size: 18, color: color),
              const SizedBox(width: 6),
              Text(
                label,
                style: TextStyle(
                  fontSize: 13,
                  fontFamily: 'Inter',
                  color: color.withValues(alpha: 0.7),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            crossAxisAlignment: CrossAxisAlignment.baseline,
            textBaseline: TextBaseline.alphabetic,
            children: [
              Text(
                value,
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.w800,
                  fontFamily: 'Inter',
                  color: color,
                ),
              ),
              const SizedBox(width: 4),
              Text(
                suffix,
                style: TextStyle(
                  fontSize: 14,
                  fontFamily: 'Inter',
                  color: color.withValues(alpha: 0.6),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildDirectReferralsSection() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.04),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
            child: Row(
              children: [
                const Icon(Icons.people_outline, size: 18, color: Color(0xFFD4AF37)),
                const SizedBox(width: 6),
                const Text(
                  '直推预种明细',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w700,
                    fontFamily: 'Inter',
                    color: Color(0xFF5D4037),
                  ),
                ),
                const Spacer(),
                Text(
                  '共 ${_directReferrals.length} 人',
                  style: const TextStyle(
                    fontSize: 13,
                    fontFamily: 'Inter',
                    color: Color(0xFF8D6E63),
                  ),
                ),
              ],
            ),
          ),
          const Divider(height: 1, color: Color(0xFFF5F0E8)),
          if (_directReferrals.isEmpty)
            const Padding(
              padding: EdgeInsets.all(24),
              child: Center(
                child: Text(
                  '暂无直推成员',
                  style: TextStyle(fontSize: 14, color: Color(0xFFBDBDBD)),
                ),
              ),
            )
          else
            ..._directReferrals.asMap().entries.map((entry) {
              final index = entry.key;
              final item = entry.value;
              return _buildMemberRow(
                item.accountSequence,
                item.selfPrePlantingPortions,
                isLast: index == _directReferrals.length - 1,
              );
            }),
        ],
      ),
    );
  }

  Widget _buildTeamMembersSection() {
    if (!_hasCompanyRole) {
      // 普通用户提示
      return Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white.withValues(alpha: 0.6),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: const Color(0xFFE0D6C2), width: 1),
        ),
        child: const Column(
          children: [
            Icon(Icons.lock_outline, size: 32, color: Color(0xFFBDBDBD)),
            SizedBox(height: 8),
            Text(
              '团队成员预种明细',
              style: TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.w600,
                fontFamily: 'Inter',
                color: Color(0xFF8D6E63),
              ),
            ),
            SizedBox(height: 4),
            Text(
              '仅市公司/省公司管理者可查看完整团队预种ID明细',
              style: TextStyle(fontSize: 13, color: Color(0xFFBDBDBD)),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      );
    }

    // 市/省公司管理者：显示全部团队成员
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.04),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
            child: Row(
              children: [
                const Icon(Icons.groups_outlined, size: 18, color: Color(0xFF2E7D32)),
                const SizedBox(width: 6),
                const Text(
                  '全部团队成员预种',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w700,
                    fontFamily: 'Inter',
                    color: Color(0xFF5D4037),
                  ),
                ),
                const Spacer(),
                Text(
                  '$_memberTotal 人有预种',
                  style: const TextStyle(
                    fontSize: 13,
                    fontFamily: 'Inter',
                    color: Color(0xFF8D6E63),
                  ),
                ),
              ],
            ),
          ),
          const Divider(height: 1, color: Color(0xFFF5F0E8)),
          if (_teamMembers.isEmpty && !_isLoadingMembers)
            const Padding(
              padding: EdgeInsets.all(24),
              child: Center(
                child: Text(
                  '暂无团队成员有预种',
                  style: TextStyle(fontSize: 14, color: Color(0xFFBDBDBD)),
                ),
              ),
            )
          else ...[
            ..._teamMembers.asMap().entries.map((entry) {
              final index = entry.key;
              final item = entry.value;
              return _buildMemberRow(
                item.accountSequence,
                item.selfPrePlantingPortions,
                isLast: index == _teamMembers.length - 1 && !_memberHasMore,
              );
            }),
            if (_isLoadingMembers)
              const Padding(
                padding: EdgeInsets.all(16),
                child: Center(
                  child: SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      color: Color(0xFFD4AF37),
                    ),
                  ),
                ),
              )
            else if (_memberHasMore)
              GestureDetector(
                onTap: _loadMoreMembers,
                child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 14),
                  child: const Center(
                    child: Text(
                      '加载更多...',
                      style: TextStyle(
                        fontSize: 14,
                        fontFamily: 'Inter',
                        color: Color(0xFFD4AF37),
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
              ),
          ],
        ],
      ),
    );
  }

  Widget _buildMemberRow(String accountSequence, int portions, {bool isLast = false}) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        border: isLast
            ? null
            : const Border(bottom: BorderSide(color: Color(0xFFF5F0E8), width: 0.5)),
      ),
      child: Row(
        children: [
          // 用户图标
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: portions > 0
                  ? const Color(0xFFD4AF37).withValues(alpha: 0.1)
                  : const Color(0xFFBDBDBD).withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(
              Icons.person_outline,
              size: 18,
              color: portions > 0 ? const Color(0xFFD4AF37) : const Color(0xFFBDBDBD),
            ),
          ),
          const SizedBox(width: 12),
          // 序列号
          Expanded(
            child: Text(
              accountSequence,
              style: const TextStyle(
                fontSize: 14,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                color: Color(0xFF5D4037),
                letterSpacing: 0.5,
              ),
            ),
          ),
          // 份数
          Text(
            '$portions 份',
            style: TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.w700,
              fontFamily: 'Inter',
              color: portions > 0 ? const Color(0xFFD4AF37) : const Color(0xFFBDBDBD),
            ),
          ),
        ],
      ),
    );
  }
}
