import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import 'package:fl_chart/fl_chart.dart';

import '../../services/auth_service.dart';
import '../../services/club_service.dart';
import '../../services/member_service.dart';
import '../../services/score_service.dart';
import '../../models/member_model.dart';
import '../../models/score_model.dart';
import 'member_statistics_screen.dart';
import 'score_entry_screen.dart';

class ClubStatisticsScreen extends StatefulWidget {
  const ClubStatisticsScreen({super.key});

  @override
  State<ClubStatisticsScreen> createState() => _ClubStatisticsScreenState();
}

class _ClubStatisticsScreenState extends State<ClubStatisticsScreen> {
  bool _isLoading = false;
  bool _isInit = false;

  Map<String, ScoreStatistics> _clubStatistics = {};
  List<Member> _members = [];
  Map<String, List<Score>> _recentScores = {};

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (!_isInit) {
      _loadClubStatistics();
      _isInit = true;
    }
  }

  Future<void> _loadClubStatistics() async {
    setState(() {
      _isLoading = true;
    });
    // await 이전에 messenger 캡처하여 안전하게 사용
    final messenger = ScaffoldMessenger.of(context);
    try {
      final authService = Provider.of<AuthService>(context, listen: false);
      final clubService = Provider.of<ClubService>(context, listen: false);
      final memberService = Provider.of<MemberService>(context, listen: false);
      final scoreService = Provider.of<ScoreService>(context, listen: false);

      if (clubService.currentClub != null) {
        // 점수 서비스 초기화
        scoreService.initialize(authService.token!);

        // 회원 목록 로드
        await memberService.fetchClubMembers();
        _members = memberService.members;

        // 클럽 통계 로드
        _clubStatistics = await scoreService.fetchClubStatistics();

        // 각 회원별 최근 점수 로드 (최대 3개)
        _recentScores = {};
        for (final member in _members) {
          try {
            final scores = await scoreService.fetchMemberScores(member.id);
            // 날짜 기준 정렬 (최신순)
            scores.sort((a, b) => b.date.compareTo(a.date));
            _recentScores[member.id] = scores.take(3).toList();
          } catch (e) {
            // 개별 회원 점수 로드 실패 시 빈 배열로 처리
            _recentScores[member.id] = [];
          }
        }
      }
    } catch (e) {
      messenger.showSnackBar(
        SnackBar(content: Text('데이터 로드 중 오류가 발생했습니다: $e')),
      );
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('클럽 통계')),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
              onRefresh: _loadClubStatistics,
              child: SingleChildScrollView(
                physics: const AlwaysScrollableScrollPhysics(),
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 클럽 전체 통계
                    _buildClubOverallStats(),
                    const SizedBox(height: 24),

                    // 회원별 통계
                    const Text(
                      '회원별 통계',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 16),

                    // 회원 목록
                    ..._members.map((member) => _buildMemberStatsCard(member)),
                  ],
                ),
              ),
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          await Navigator.of(context).push(
            MaterialPageRoute(builder: (context) => const ScoreEntryScreen()),
          );
          // 화면으로 돌아왔을 때 데이터 새로고침
          _loadClubStatistics();
        },
        backgroundColor: Colors.blue,
        child: const Icon(Icons.add, color: Colors.white),
      ),
    );
  }

  Widget _buildClubOverallStats() {
    // 클럽 전체 통계가 없는 경우
    if (!_clubStatistics.containsKey('overall')) {
      return const Card(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Center(child: Text('클럽 전체 통계 데이터가 없습니다')),
        ),
      );
    }

    final overallStats = _clubStatistics['overall']!;

    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '클럽 전체 통계',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: _buildStatItem(
                    label: '클럽 평균',
                    value: overallStats.average.toStringAsFixed(1),
                    icon: Icons.score,
                    color: Colors.blue,
                  ),
                ),
                Expanded(
                  child: _buildStatItem(
                    label: '최고 점수',
                    value: overallStats.highScore.toString(),
                    icon: Icons.emoji_events,
                    color: Colors.amber,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: _buildStatItem(
                    label: '최저 점수',
                    value: overallStats.lowScore.toString(),
                    icon: Icons.arrow_downward,
                    color: Colors.red,
                  ),
                ),
                Expanded(
                  child: _buildStatItem(
                    label: '총 게임 수',
                    value: overallStats.gamesPlayed.toString(),
                    icon: Icons.sports,
                    color: Colors.green,
                  ),
                ),
              ],
            ),

            // 클럽 평균 점수 추이 그래프
            const SizedBox(height: 24),
            const Text(
              '클럽 평균 점수 추이',
              style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            SizedBox(height: 180, child: _buildClubAverageChart()),

            // 추가 통계 정보
            if (overallStats.additionalStats != null) ...[
              const SizedBox(height: 16),
              const Divider(),
              const SizedBox(height: 8),
              ...overallStats.additionalStats!.entries.map((entry) {
                return Padding(
                  padding: const EdgeInsets.only(bottom: 8.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(entry.key, style: const TextStyle(fontSize: 14)),
                      Text(
                        entry.value.toString(),
                        style: const TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                );
              }),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildStatItem({
    required String label,
    required String value,
    required IconData icon,
    required Color color,
  }) {
    return Column(
      children: [
        Icon(icon, size: 28, color: color),
        const SizedBox(height: 8),
        Text(
          value,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        Text(label, style: TextStyle(fontSize: 12, color: Colors.grey[600])),
      ],
    );
  }

  Widget _buildMemberStatsCard(Member member) {
    // 회원 통계 정보
    final memberStats = _clubStatistics[member.id];
    // 회원 최근 점수
    final recentScores = _recentScores[member.id] ?? [];

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => MemberStatisticsScreen(memberId: member.id),
            ),
          );
        },
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 회원 정보
              Row(
                children: [
                  CircleAvatar(
                    radius: 24,
                    backgroundColor: Colors.blue.shade100,
                    backgroundImage: member.profileImage != null
                        ? NetworkImage(member.profileImage!)
                        : null,
                    child: member.profileImage == null
                        ? Text(
                            member.name.isNotEmpty
                                ? member.name[0].toUpperCase()
                                : '?',
                            style: const TextStyle(
                              fontSize: 20,
                              color: Colors.blue,
                              fontWeight: FontWeight.bold,
                            ),
                          )
                        : null,
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          member.name,
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        if (memberStats != null)
                          Text(
                            '평균: ${memberStats.average.toStringAsFixed(1)} | 최고: ${memberStats.highScore} | 게임: ${memberStats.gamesPlayed}',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey[600],
                            ),
                          ),
                      ],
                    ),
                  ),
                  const Icon(Icons.chevron_right),
                ],
              ),

              // 최근 점수 표시
              if (recentScores.isNotEmpty) ...[
                const SizedBox(height: 12),
                const Divider(),
                const SizedBox(height: 8),
                const Text(
                  '최근 점수',
                  style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: recentScores.map((score) {
                    return Column(
                      children: [
                        Text(
                          score.totalScore.toString(),
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.blue,
                          ),
                        ),
                        Text(
                          DateFormat('MM/dd').format(score.date),
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    );
                  }).toList(),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildClubAverageChart() {
    // 클럽 통계가 없는 경우
    if (!_clubStatistics.containsKey('overall')) {
      return const Center(child: Text('통계 데이터가 없습니다'));
    }

    // 회원별 평균 점수 데이터 추출
    final memberAverages = <String, double>{};

    // 회원별 통계 정보에서 평균 점수 추출
    _clubStatistics.forEach((key, stats) {
      if (key != 'overall') {
        // 회원 ID에 해당하는 회원 찾기
        final member = _members.firstWhere(
          (m) => m.id == key,
          orElse: () => Member(
            id: key,
            userId: key,
            name: 'Unknown',
            email: '',
            clubId: '',
            isActive: true,
          ),
        );
        memberAverages[member.name] = stats.average;
      }
    });

    // 평균 점수 기준으로 정렬 (내림차순)
    final sortedEntries = memberAverages.entries.toList()
      ..sort((a, b) => b.value.compareTo(a.value));

    // 최대 8명만 표시
    final displayEntries = sortedEntries.length > 8
        ? sortedEntries.sublist(0, 8)
        : sortedEntries;

    // 그래프 데이터 생성
    final barGroups = <BarChartGroupData>[];
    for (int i = 0; i < displayEntries.length; i++) {
      barGroups.add(
        BarChartGroupData(
          x: i,
          barRods: [
            BarChartRodData(
              toY: displayEntries[i].value,
              color: Colors.blue,
              width: 16,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(4),
                topRight: Radius.circular(4),
              ),
            ),
          ],
        ),
      );
    }

    // 최소/최대 점수 계산 (Y축 범위 설정용)
    final minScore = displayEntries.isEmpty
        ? 0.0
        : displayEntries.map((e) => e.value).reduce((a, b) => a < b ? a : b) -
              10;
    final maxScore = displayEntries.isEmpty
        ? 300.0
        : displayEntries.map((e) => e.value).reduce((a, b) => a > b ? a : b) +
              10;

    return BarChart(
      BarChartData(
        alignment: BarChartAlignment.spaceAround,
        maxY: maxScore,
        minY: minScore < 0 ? 0 : minScore,
        gridData: const FlGridData(show: true, horizontalInterval: 50),
        borderData: FlBorderData(
          show: true,
          border: Border.all(color: Colors.grey.shade300),
        ),
        titlesData: FlTitlesData(
          show: true,
          rightTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          topTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              getTitlesWidget: (value, meta) {
                final index = value.toInt();
                if (index >= 0 && index < displayEntries.length) {
                  // 회원 이름 표시 (최대 5글자)
                  final name = displayEntries[index].key;
                  final shortName = name.length > 5
                      ? '${name.substring(0, 4)}...'
                      : name;

                  return Text(shortName, style: const TextStyle(fontSize: 10));
                }
                return const SizedBox();
              },
              reservedSize: 30,
            ),
          ),
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              interval: 50,
              getTitlesWidget: (value, meta) {
                return Text(
                  value.toInt().toString(),
                  style: const TextStyle(fontSize: 10),
                );
              },
              reservedSize: 40,
            ),
          ),
        ),
        barGroups: barGroups,
      ),
    );
  }
}
