import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../core/theme/app_colors.dart';
import '../../../../core/theme/app_text_styles.dart';
import '../../../../core/theme/app_spacing.dart';
import '../../../../core/theme/app_radius.dart';
import '../../../../core/widgets/fs_button.dart';
import '../../../../core/widgets/fs_badge.dart';
import '../bloc/quiz_cubit.dart';
import '../bloc/quiz_state.dart';
import 'quiz_review_screen.dart';

class QuizResultsScreen extends StatefulWidget {
  final QuizCubit cubit;

  const QuizResultsScreen({super.key, required this.cubit});

  @override
  State<QuizResultsScreen> createState() => _QuizResultsScreenState();
}

class _QuizResultsScreenState extends State<QuizResultsScreen>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _scoreAnim;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1500),
    );

    final s = widget.cubit.state;
    final target = s is QuizResults ? s.result.percentage / 100.0 : 0.0;

    _scoreAnim = Tween<double>(begin: 0, end: target).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeOutCubic),
    );
    _controller.forward();
  }

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<QuizCubit, QuizState>(
      bloc: widget.cubit,
      builder: (context, state) {
        if (state is! QuizResults) return const SizedBox.shrink();

        final result = state.result;
        final scoreColor = result.percentage >= 70
            ? AppColors.success
            : result.percentage >= 40
                ? AppColors.warning
                : AppColors.error;

        return ListView(
          padding: AppSpacing.screenAll,
          children: [
            AppSpacing.vLg,

            // Animated score circle
            Center(
              child: AnimatedBuilder(
                animation: _scoreAnim,
                builder: (_, __) {
                  final pct = (_scoreAnim.value * 100).round();
                  return SizedBox(
                    width: 140,
                    height: 140,
                    child: CustomPaint(
                      painter: _ScoreRingPainter(
                        progress: _scoreAnim.value,
                        color: scoreColor,
                      ),
                      child: Center(
                        child: Text(
                          '$pct%',
                          style: AppTextStyles.displayLarge.copyWith(
                            color: scoreColor,
                            fontWeight: FontWeight.w900,
                            fontSize: 42,
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
            AppSpacing.vLg,

            Center(
              child: Text(
                'You scored ${result.percentage}%',
                style: AppTextStyles.headlineLarge,
              ),
            ),
            Center(
              child: Text(
                '${result.correct} out of ${result.total} correct',
                style: AppTextStyles.bodyMedium
                    .copyWith(color: AppColors.textSecondary),
              ),
            ),
            AppSpacing.vXl,

            // Per-question results
            ...List.generate(result.results.length, (i) {
              final r = result.results[i];
              final q = i < state.questions.length ? state.questions[i] : null;

              return Container(
                margin: const EdgeInsets.only(bottom: 10),
                padding: AppSpacing.cardInner,
                decoration: BoxDecoration(
                  color: AppColors.panel,
                  border: Border.all(color: AppColors.border),
                  borderRadius: AppRadius.smAll,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            q?.title ?? 'Question ${i + 1}',
                            style: AppTextStyles.titleSmall,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SizedBox(width: 8),
                        FSBadge(
                          text: r.isCorrect ? '✓ Correct' : '✗ Wrong',
                          variant: r.isCorrect
                              ? FSBadgeVariant.green
                              : FSBadgeVariant.red,
                        ),
                      ],
                    ),
                    if (!r.isCorrect) ...[
                      const SizedBox(height: 8),
                      Text(
                        'Your answer: ${r.selectedAnswer}',
                        style: AppTextStyles.bodySmall
                            .copyWith(color: AppColors.errorLight),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      Text(
                        'Correct: ${r.correctAnswer}',
                        style: AppTextStyles.bodySmall
                            .copyWith(color: AppColors.successLight),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ],
                ),
              );
            }),

            AppSpacing.vLg,

            FSButton(
              label: '📖 Review All Answers',
              onPressed: () {
                Navigator.of(context).push(MaterialPageRoute(
                  builder: (_) => QuizReviewScreen(
                    questions: state.questions,
                    userAnswers: state.userAnswers,
                    results: result.results,
                  ),
                ));
              },
              variant: FSButtonVariant.secondary,
            ),
            AppSpacing.vSm,
            FSButton(
              label: '🔄 Try Again',
              onPressed: () => widget.cubit.reset(),
              variant: FSButtonVariant.gradient,
            ),
            AppSpacing.vXl,
          ],
        );
      },
    );
  }
}

class _ScoreRingPainter extends CustomPainter {
  final double progress;
  final Color color;

  _ScoreRingPainter({required this.progress, required this.color});

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = (size.width - 12) / 2;

    canvas.drawCircle(
      center,
      radius,
      Paint()
        ..color = AppColors.border
        ..style = PaintingStyle.stroke
        ..strokeWidth = 8,
    );

    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius),
      -math.pi / 2,
      2 * math.pi * progress,
      false,
      Paint()
        ..color = color
        ..style = PaintingStyle.stroke
        ..strokeWidth = 8
        ..strokeCap = StrokeCap.round,
    );
  }

  @override
  bool shouldRepaint(_ScoreRingPainter old) =>
      old.progress != progress || old.color != color;
}