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_error_state.dart';
import '../bloc/quiz_cubit.dart';
import '../bloc/quiz_state.dart';
import 'quiz_question_screen.dart';
import 'quiz_results_screen.dart';

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

  @override
  State<QuizSetupScreen> createState() => _QuizSetupScreenState();
}

class _QuizSetupScreenState extends State<QuizSetupScreen> {
  late final QuizCubit _cubit;
  int _numQuestions = 5;
  String? _difficulty;
  String? _category;

  @override
  void initState() {
    super.initState();
    _cubit = QuizCubit()..loadFilters();
  }

  @override
  void dispose() {
    _cubit.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
      value: _cubit,
      child: Scaffold(
        body: SafeArea(
          child: BlocConsumer<QuizCubit, QuizState>(
            listener: (context, state) {},
            builder: (context, state) {
              if (state is QuizActive) {
                return QuizQuestionScreen(cubit: _cubit);
              }
              if (state is QuizStarting || state is QuizSubmitting) {
                return const Center(child: CircularProgressIndicator());
              }
              if (state is QuizResults) {
                return QuizResultsScreen(cubit: _cubit);
              }
              if (state is QuizError) {
                return FSErrorState(
                  message: state.message,
                  onRetry: () => _cubit.reset(),
                );
              }
              return _buildSetupForm(state as QuizSetup);
            },
          ),
        ),
      ),
    );
  }

  Widget _buildSetupForm(QuizSetup state) {
    final filters = state.filters;

    return ListView(
      padding: AppSpacing.screenAll,
      children: [
        Text('Practice MCQ', style: AppTextStyles.headlineLarge),
        AppSpacing.vXs,
        Text('Test your knowledge with real financial scenarios',
            style: AppTextStyles.bodySmall),
        AppSpacing.vXl,

        Container(
          padding: AppSpacing.cardInnerLarge,
          decoration: BoxDecoration(
            color: AppColors.panel,
            border: Border.all(color: AppColors.border),
            borderRadius: AppRadius.mdAll,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Start a New Quiz', style: AppTextStyles.titleMedium),
              AppSpacing.vLg,

              // Number of questions
              Text('NUMBER OF QUESTIONS',
                  style: AppTextStyles.labelSmall.copyWith(
                      color: AppColors.textSecondary, letterSpacing: 1)),
              AppSpacing.vSm,
              Row(
                children: [5, 10, 15, 20].map((n) {
                  final selected = _numQuestions == n;
                  return Expanded(
                    child: GestureDetector(
                      onTap: () => setState(() => _numQuestions = n),
                      child: Container(
                        margin: const EdgeInsets.only(right: 8),
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        decoration: BoxDecoration(
                          color: selected
                              ? AppColors.accentGlow
                              : AppColors.bgSecondary,
                          border: Border.all(
                            color: selected
                                ? AppColors.accent
                                : AppColors.border,
                            width: selected ? 1.5 : 1,
                          ),
                          borderRadius: AppRadius.smAll,
                        ),
                        alignment: Alignment.center,
                        child: Text(
                          '$n',
                          style: AppTextStyles.titleSmall.copyWith(
                            color: selected
                                ? AppColors.accentLight
                                : AppColors.textSecondary,
                          ),
                        ),
                      ),
                    ),
                  );
                }).toList(),
              ),
              AppSpacing.vLg,

              // Difficulty
              Text('DIFFICULTY',
                  style: AppTextStyles.labelSmall.copyWith(
                      color: AppColors.textSecondary, letterSpacing: 1)),
              const SizedBox(height: 6),
              _buildDropdown(
                value: _difficulty,
                hint: 'All Difficulties',
                items: filters?.difficulties ?? [],
                onChanged: (v) => setState(() => _difficulty = v),
              ),
              AppSpacing.vMd,

              // Category
              Text('CATEGORY',
                  style: AppTextStyles.labelSmall.copyWith(
                      color: AppColors.textSecondary, letterSpacing: 1)),
              const SizedBox(height: 6),
              _buildDropdown(
                value: _category,
                hint: 'All Categories',
                items: filters?.categories ?? [],
                onChanged: (v) => setState(() => _category = v),
              ),
            ],
          ),
        ),
        AppSpacing.vLg,

        FSButton(
          label: '🚀 Start Quiz',
          isLoading: state.isLoadingFilters,
          onPressed: state.isLoadingFilters
              ? null
              : () => _cubit.startQuiz(
                    numQuestions: _numQuestions,
                    difficulty: _difficulty,
                    category: _category,
                  ),
          variant: FSButtonVariant.gradient,
        ),
      ],
    );
  }

  Widget _buildDropdown({
    required String? value,
    required String hint,
    required List<String> items,
    required ValueChanged<String?> onChanged,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        color: AppColors.bgSecondary,
        border: Border.all(color: AppColors.border),
        borderRadius: AppRadius.smAll,
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          value: value,
          hint: Text(hint,
              style: AppTextStyles.bodySmall
                  .copyWith(color: AppColors.textTertiary)),
          isExpanded: true,
          dropdownColor: AppColors.panelLight,
          style: AppTextStyles.bodyMedium,
          items: [
            DropdownMenuItem<String>(
              value: null,
              child: Text(hint,
                  style: AppTextStyles.bodySmall
                      .copyWith(color: AppColors.textTertiary)),
            ),
            ...items.map((item) => DropdownMenuItem(
                  value: item,
                  child: Text(item, style: AppTextStyles.bodySmall),
                )),
          ],
          onChanged: onChanged,
        ),
      ),
    );
  }
}