import 'package:flutter/material.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_badge.dart';
import '../../../../core/widgets/option_button.dart';
import '../../data/datasources/quiz_remote_datasource.dart';

class QuizReviewScreen extends StatefulWidget {
  final List<QuizQuestionModel> questions;
  final List<String?> userAnswers;
  final List<QuizAnswerResultModel> results;

  const QuizReviewScreen({
    super.key,
    required this.questions,
    required this.userAnswers,
    required this.results,
  });

  @override
  State<QuizReviewScreen> createState() => _QuizReviewScreenState();
}

class _QuizReviewScreenState extends State<QuizReviewScreen> {
  String _filter = 'all'; // 'all', 'correct', 'wrong'

  List<int> get _filteredIndices {
    final indices = <int>[];
    for (var i = 0; i < widget.results.length; i++) {
      if (_filter == 'all') {
        indices.add(i);
      } else if (_filter == 'correct' && widget.results[i].isCorrect) {
        indices.add(i);
      } else if (_filter == 'wrong' && !widget.results[i].isCorrect) {
        indices.add(i);
      }
    }
    return indices;
  }

  @override
  Widget build(BuildContext context) {
    final filtered = _filteredIndices;

    return Scaffold(
      appBar: AppBar(title: const Text('Review Answers')),
      body: Column(
        children: [
          // Filter pills
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
            child: Row(
              children: [
                _filterChip('All', 'all'),
                const SizedBox(width: 8),
                _filterChip('✓ Correct', 'correct'),
                const SizedBox(width: 8),
                _filterChip('✗ Wrong', 'wrong'),
              ],
            ),
          ),

          Expanded(
            child: filtered.isEmpty
                ? Center(
                    child: Text('No questions match this filter.',
                        style: AppTextStyles.bodySmall
                            .copyWith(color: AppColors.textTertiary)),
                  )
                : ListView.builder(
                    padding: AppSpacing.screenH,
                    itemCount: filtered.length,
                    itemBuilder: (context, idx) {
                      final i = filtered[idx];
                      return _buildQuestionReview(i);
                    },
                  ),
          ),
        ],
      ),
    );
  }

  Widget _filterChip(String label, String value) {
    final selected = _filter == value;
    return GestureDetector(
      onTap: () => setState(() => _filter = value),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
        decoration: BoxDecoration(
          color: selected ? AppColors.accentGlow : AppColors.panel,
          border: Border.all(
            color: selected ? AppColors.accent : AppColors.border,
          ),
          borderRadius: AppRadius.pill,
        ),
        child: Text(
          label,
          style: AppTextStyles.labelMedium.copyWith(
            color: selected ? AppColors.accentLight : AppColors.textSecondary,
          ),
        ),
      ),
    );
  }

  Widget _buildQuestionReview(int index) {
    final q = widget.questions[index];
    final r = widget.results[index];
    final selectedLabel = widget.userAnswers[index];

    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: AppSpacing.cardInner,
      decoration: BoxDecoration(
        color: AppColors.panel,
        border: Border.all(color: AppColors.border),
        borderRadius: AppRadius.mdAll,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Header
          Row(
            children: [
              Text('Q${index + 1}',
                  style: AppTextStyles.titleSmall
                      .copyWith(color: AppColors.accentLight)),
              const SizedBox(width: 8),
              Expanded(
                child: Text(q.title,
                    style: AppTextStyles.titleSmall,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis),
              ),
              FSBadge(
                text: r.isCorrect ? 'Correct' : 'Wrong',
                variant:
                    r.isCorrect ? FSBadgeVariant.green : FSBadgeVariant.red,
              ),
            ],
          ),

          // Scenario
          if (q.scenarioParagraph != null &&
              q.scenarioParagraph!.isNotEmpty) ...[
            AppSpacing.vSm,
            Text(
              q.scenarioParagraph!,
              style: AppTextStyles.bodySmall
                  .copyWith(color: AppColors.textTertiary, height: 1.6),
              maxLines: 4,
              overflow: TextOverflow.ellipsis,
            ),
          ],
          AppSpacing.vMd,

          // Options
          ...q.options.map((opt) {
            OptionState optState;
            if (opt.label == q.correctLabel) {
              optState = OptionState.correct;
            } else if (opt.label == selectedLabel) {
              optState = OptionState.wrong;
            } else {
              optState = OptionState.idle;
            }

            return Padding(
              padding: const EdgeInsets.only(bottom: 6),
              child: OptionButton(
                label: opt.label,
                text: opt.text,
                state: optState,
              ),
            );
          }),

          // Rationale
          if (r.correctRationale != null) ...[
            AppSpacing.vSm,
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: AppColors.successBg,
                borderRadius: AppRadius.smAll,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('Why the correct answer is right:',
                      style: AppTextStyles.labelSmall
                          .copyWith(color: AppColors.successLight)),
                  const SizedBox(height: 4),
                  Text(r.correctRationale!,
                      style: AppTextStyles.bodySmall.copyWith(height: 1.6)),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }
}