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 '../../../../core/widgets/option_button.dart';
import '../../../../core/widgets/givens_table_widget.dart';
import '../bloc/quiz_cubit.dart';
import '../bloc/quiz_state.dart';

class QuizQuestionScreen extends StatelessWidget {
  final QuizCubit cubit;

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

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

        final q = state.currentQuestion;
        final selectedLabel = state.userAnswers[state.currentIndex];
        final revealed = state.currentRevealed;

        return Column(
          children: [
            // Progress bar
            Container(
              padding: const EdgeInsets.fromLTRB(20, 12, 20, 8),
              child: Row(
                children: [
                  Expanded(
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(3),
                      child: LinearProgressIndicator(
                        value: (state.currentIndex + 1) / state.totalQuestions,
                        minHeight: 6,
                        backgroundColor: AppColors.border,
                        valueColor:
                            const AlwaysStoppedAnimation(AppColors.accent),
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Text(
                    '${state.currentIndex + 1}/${state.totalQuestions}',
                    style: AppTextStyles.labelMedium
                        .copyWith(color: AppColors.textSecondary),
                  ),
                ],
              ),
            ),

            // Scrollable content
            Expanded(
              child: ListView(
                padding: AppSpacing.screenH,
                children: [
                  AppSpacing.vSm,

                  // Title + badges
                  Text(q.title, style: AppTextStyles.titleMedium),
                  AppSpacing.vSm,
                  Wrap(
                    spacing: 6,
                    runSpacing: 6,
                    children: [
                      if (q.riskLevel != null) FSBadge.risk(q.riskLevel!),
                      if (q.difficulty != null)
                        FSBadge.difficulty(q.difficulty!),
                      if (q.eventType != null)
                        FSBadge(
                          text: q.eventType!,
                          variant: q.eventType!.toLowerCase() == 'major'
                              ? FSBadgeVariant.red
                              : FSBadgeVariant.blue,
                        ),
                    ],
                  ),
                  AppSpacing.vMd,

                  // Scenario paragraph
                  if (q.scenarioParagraph != null &&
                      q.scenarioParagraph!.isNotEmpty)
                    Container(
                      padding: const EdgeInsets.all(14),
                      decoration: BoxDecoration(
                        color: AppColors.bgSecondary,
                        borderRadius: AppRadius.smAll,
                        border: Border(
                          left: BorderSide(
                              color: AppColors.accent, width: 3),
                        ),
                      ),
                      child: Text(
                        q.scenarioParagraph!,
                        style: AppTextStyles.bodyMedium
                            .copyWith(color: AppColors.textSecondary, height: 1.7),
                      ),
                    ),
                  AppSpacing.vMd,

                  // Givens table
                  if (q.givensTable != null && q.givensTable!.isNotEmpty)
                    GivensTableWidget(data: q.givensTable!),
                  if (q.givensTable != null && q.givensTable!.isNotEmpty)
                    AppSpacing.vMd,

                  // Options
                  ...q.options.map((opt) {
                    OptionState optState;
                    if (!revealed) {
                      optState = selectedLabel == opt.label
                          ? OptionState.selected
                          : OptionState.idle;
                    } else {
                      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: 8),
                      child: OptionButton(
                        label: opt.label,
                        text: opt.text,
                        state: optState,
                        onTap: revealed
                            ? null
                            : () => cubit.selectAnswer(opt.label),
                      ),
                    );
                  }),

                  // Explanation
                  if (revealed && selectedLabel != null) ...[
                    AppSpacing.vSm,
                    _buildExplanation(q, selectedLabel),
                  ],

                  AppSpacing.vLg,

                  // Navigation buttons
                  if (revealed) ...[
                    if (!state.isLastQuestion)
                      FSButton(
                        label: 'Next Question →',
                        onPressed: () => cubit.nextQuestion(),
                      )
                    else
                      FSButton(
                        label: '✓ Finish Quiz',
                        onPressed: () => cubit.submitQuiz(),
                        variant: FSButtonVariant.gradient,
                      ),
                  ],
                  AppSpacing.vXl,
                ],
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildExplanation(QuizQuestionModel q, String selectedLabel) {
    final isCorrect = selectedLabel == q.correctLabel;
    final selectedOpt =
        q.options.where((o) => o.label == selectedLabel).firstOrNull;
    final explanation = selectedOpt != null
        ? q.getExplanation(selectedOpt.text)
        : 'No explanation available.';

    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: isCorrect ? AppColors.successBg : AppColors.errorBg,
        border: Border.all(
          color: isCorrect
              ? AppColors.success.withOpacity(0.2)
              : AppColors.error.withOpacity(0.2),
        ),
        borderRadius: AppRadius.smAll,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            isCorrect ? '✅ Correct!' : '❌ Incorrect',
            style: AppTextStyles.titleSmall.copyWith(
              color: isCorrect ? AppColors.successLight : AppColors.errorLight,
            ),
          ),
          const SizedBox(height: 6),
          Text(
            explanation,
            style: AppTextStyles.bodySmall.copyWith(height: 1.6),
          ),
          if (!isCorrect && q.bestAnswerRationale != null) ...[
            const SizedBox(height: 10),
            Text(
              'Correct answer rationale:',
              style: AppTextStyles.labelSmall
                  .copyWith(color: AppColors.successLight),
            ),
            const SizedBox(height: 4),
            Text(
              q.bestAnswerRationale!,
              style: AppTextStyles.bodySmall
                  .copyWith(color: AppColors.textSecondary, height: 1.6),
            ),
          ],
        ],
      ),
    );
  }
}