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 'score_entry_screen.dart';
import '../../widgets/dialog_actions.dart';

class MemberStatisticsScreen extends StatefulWidget {
  final String memberId;

  const MemberStatisticsScreen({super.key, required this.memberId});

  @override
  State<MemberStatisticsScreen> createState() => _MemberStatisticsScreenState();
}

class _MemberStatisticsScreenState extends State<MemberStatisticsScreen>
    with SingleTickerProviderStateMixin {
  bool _isLoading = false;
  bool _isInit = false;
  late TabController _tabController;

  Member? _member;
  List<Score> _scores = [];
  ScoreStatistics? _statistics;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

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

  Future<void> _loadMemberData() async {
    setState(() {
      _isLoading = true;
    });

    // await 이전에 messenger 캡처
    final messenger = ScaffoldMessenger.of(context);

    try {
      final authService = Provider.of<AuthService>(context, listen: false);
      final memberService = Provider.of<MemberService>(context, listen: false);
      final scoreService = Provider.of<ScoreService>(context, listen: false);
      final clubService = Provider.of<ClubService>(context, listen: false);
      
      if (clubService.currentClub != null) {
        // 회원 정보 로드
        _member = await memberService.fetchMemberById(widget.memberId);

        // 점수 서비스 초기화
        scoreService.initialize(authService.token!);

        // 회원 점수 및 통계 로드
        await Future.wait([
          scoreService.fetchMemberScores(widget.memberId).then((scores) {
            _scores = scores;
          }),
          scoreService.fetchMemberStatistics(widget.memberId).then((stats) {
            _statistics = stats;
          }),
        ]);
      }
    } catch (e) {
      messenger.showSnackBar(
        SnackBar(content: Text('데이터 로드 중 오류가 발생했습니다: $e')),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_member?.name ?? '회원 통계'),
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '통계'),
            Tab(text: '점수 기록'),
          ],
        ),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : TabBarView(
              controller: _tabController,
              children: [_buildStatisticsTab(), _buildScoresTab()],
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          await Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => ScoreEntryScreen(memberId: widget.memberId),
            ),
          );
          // 화면으로 돌아왔을 때 데이터 새로고침
          _loadMemberData();
        },
        backgroundColor: Colors.blue,
        child: const Icon(Icons.add, color: Colors.white),
      ),
    );
  }

  Widget _buildStatisticsTab() {
    if (_statistics == null) {
      return const Center(child: Text('통계 데이터가 없습니다'));
    }

    return RefreshIndicator(
      onRefresh: _loadMemberData,
      child: SingleChildScrollView(
        physics: const AlwaysScrollableScrollPhysics(),
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 회원 정보 카드
            if (_member != null) _buildMemberInfoCard(),
            const SizedBox(height: 24),

            // 주요 통계 카드
            _buildMainStatsCard(),
            const SizedBox(height: 24),

            // 추가 통계 정보
            if (_statistics!.additionalStats != null)
              _buildAdditionalStatsCard(),

            // 통계 그래프
            const SizedBox(height: 24),
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '점수 추이',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 16),
                    SizedBox(height: 200, child: _buildScoreChart()),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMemberInfoCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          children: [
            CircleAvatar(
              radius: 30,
              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: 24,
                        color: Colors.blue,
                        fontWeight: FontWeight.bold,
                      ),
                    )
                  : null,
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _member!.name,
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    _member!.email,
                    style: TextStyle(color: Colors.grey[600]),
                  ),
                  if (_member!.phone != null)
                    Text(
                      _member!.phone!,
                      style: TextStyle(color: Colors.grey[600]),
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMainStatsCard() {
    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: _statistics!.average.toStringAsFixed(1),
                    icon: Icons.score,
                    color: Colors.blue,
                  ),
                ),
                Expanded(
                  child: _buildStatItem(
                    label: '최고 점수',
                    value: _statistics!.highScore.toString(),
                    icon: Icons.emoji_events,
                    color: Colors.amber,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: _buildStatItem(
                    label: '최저 점수',
                    value: _statistics!.lowScore.toString(),
                    icon: Icons.arrow_downward,
                    color: Colors.red,
                  ),
                ),
                Expanded(
                  child: _buildStatItem(
                    label: '게임 수',
                    value: _statistics!.gamesPlayed.toString(),
                    icon: Icons.sports,
                    color: Colors.green,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

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

  Widget _buildAdditionalStatsCard() {
    final additionalStats = _statistics!.additionalStats!;

    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),
            ...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: 16)),
                    Text(
                      entry.value.toString(),
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              );
            }),
          ],
        ),
      ),
    );
  }

  Widget _buildScoresTab() {
    if (_scores.isEmpty) {
      return const Center(child: Text('기록된 점수가 없습니다'));
    }

    // 날짜 기준으로 정렬 (최신순)
    final sortedScores = [..._scores];
    sortedScores.sort((a, b) => b.date.compareTo(a.date));

    return RefreshIndicator(
      onRefresh: _loadMemberData,
      child: ListView.builder(
        padding: const EdgeInsets.all(8.0),
        itemCount: sortedScores.length,
        itemBuilder: (context, index) {
          final score = sortedScores[index];
          return _buildScoreCard(score);
        },
      ),
    );
  }

  Widget _buildScoreCard(Score score) {
    final dateFormat = DateFormat('yyyy년 MM월 dd일');

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: ExpansionTile(
        title: Row(
          children: [
            Text(
              score.totalScore.toString(),
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.blue,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    dateFormat.format(score.date),
                    style: const TextStyle(fontSize: 14),
                  ),
                  if (score.notes != null && score.notes!.isNotEmpty)
                    Text(
                      score.notes!,
                      style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                ],
              ),
            ),
          ],
        ),
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '프레임 점수',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                _buildFrameScores(score.frames),
                if (score.notes != null && score.notes!.isNotEmpty) ...[
                  const SizedBox(height: 16),
                  const Text(
                    '메모',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 4),
                  Text(score.notes!),
                ],
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    TextButton.icon(
                      icon: const Icon(Icons.edit, size: 16),
                      label: const Text('수정'),
                      onPressed: () {
                        // 점수 수정 기능 (추후 구현)
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('점수 수정 기능은 아직 개발 중입니다')),
                        );
                      },
                    ),
                    const SizedBox(width: 8),
                    TextButton.icon(
                      icon: const Icon(
                        Icons.delete,
                        size: 16,
                        color: Colors.red,
                      ),
                      label: const Text(
                        '삭제',
                        style: TextStyle(color: Colors.red),
                      ),
                      onPressed: () {
                        _showDeleteConfirmationDialog(score);
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFrameScores(List<int> frames) {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: List.generate(10, (index) {
          return Expanded(
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 8),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey[300]!),
              ),
              child: Column(
                children: [
                  Text(
                    '${index + 1}',
                    style: TextStyle(fontSize: 10, color: Colors.grey[600]),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    index < frames.length ? frames[index].toString() : '-',
                    style: const TextStyle(fontWeight: FontWeight.bold),
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          );
        }),
      ),
    );
  }

  Widget _buildScoreChart() {
    if (_scores.isEmpty) {
      return const Center(child: Text('점수 데이터가 없습니다'));
    }

    // 날짜 기준으로 정렬 (오래된 순)
    final sortedScores = [..._scores];
    sortedScores.sort((a, b) => a.date.compareTo(b.date));

    // 최대 10개의 최근 점수만 표시
    final displayScores = sortedScores.length > 10
        ? sortedScores.sublist(sortedScores.length - 10)
        : sortedScores;

    // 최소/최대 점수 계산 (Y축 범위 설정용)
    final minScore =
        displayScores.map((s) => s.totalScore).reduce((a, b) => a < b ? a : b) -
        10;
    final maxScore =
        displayScores.map((s) => s.totalScore).reduce((a, b) => a > b ? a : b) +
        10;

    // 그래프 데이터 포인트 생성
    final spots = <FlSpot>[];
    for (int i = 0; i < displayScores.length; i++) {
      spots.add(FlSpot(i.toDouble(), displayScores[i].totalScore.toDouble()));
    }

    return LineChart(
      LineChartData(
        gridData: FlGridData(
          show: true,
          drawVerticalLine: true,
          horizontalInterval: 20,
          verticalInterval: 1,
        ),
        titlesData: FlTitlesData(
          show: true,
          rightTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          topTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 30,
              interval: 1,
              getTitlesWidget: (value, meta) {
                final index = value.toInt();
                if (index >= 0 && index < displayScores.length) {
                  return Text(
                    DateFormat('MM/dd').format(displayScores[index].date),
                    style: const TextStyle(fontSize: 10),
                  );
                }
                return const SizedBox();
              },
            ),
          ),
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              interval: 50,
              getTitlesWidget: (value, meta) {
                return Text(
                  value.toInt().toString(),
                  style: const TextStyle(fontSize: 10),
                );
              },
              reservedSize: 40,
            ),
          ),
        ),
        borderData: FlBorderData(
          show: true,
          border: Border.all(color: Colors.grey.shade300),
        ),
        minX: 0,
        maxX: displayScores.length - 1.0,
        minY: minScore.toDouble(),
        maxY: maxScore.toDouble(),
        lineBarsData: [
          LineChartBarData(
            spots: spots,
            isCurved: false,
            color: Colors.blue,
            barWidth: 3,
            isStrokeCapRound: true,
            dotData: const FlDotData(show: true),
            belowBarData: BarAreaData(
              show: true,
              color: Colors.blue.withValues(alpha: 0.2),
            ),
          ),
        ],
      ),
    );
  }

  void _showDeleteConfirmationDialog(Score score) {
    showDialog(
      context: context,
      builder: (dialogContext) => AlertDialog(
        title: const Text('점수 삭제'),
        content: const Text('이 점수 기록을 정말 삭제하시겠습니까?'),
        actions: DialogActions.confirm(
          onCancel: () => Navigator.of(dialogContext).pop(),
          onConfirm: () async {
            // await 전에 필요한 객체 캡처
            final navigator = Navigator.of(dialogContext);
            final messenger = ScaffoldMessenger.of(dialogContext);
            final scoreService = Provider.of<ScoreService>(dialogContext, listen: false);
            navigator.pop();
            try {
              await scoreService.deleteScore(score.id);
              _loadMemberData();
              messenger.showSnackBar(const SnackBar(content: Text('점수가 삭제되었습니다')));
            } catch (e) {
              messenger.showSnackBar(SnackBar(content: Text('점수 삭제에 실패했습니다: $e')));
            }
          },
          destructive: true,
          confirmText: '삭제',
        ),
      ),
    );
  }
}
