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/utils/formatters.dart';
import '../../../../core/widgets/fs_badge.dart';
import '../../../../core/widgets/fs_error_state.dart';
import '../../../../core/widgets/givens_table_widget.dart';
import '../bloc/scenario_cubit.dart';
import '../bloc/scenario_state.dart';

class ScenarioDetailScreen extends StatefulWidget {
  final String scenarioId;

  const ScenarioDetailScreen({super.key, required this.scenarioId});

  @override
  State<ScenarioDetailScreen> createState() => _ScenarioDetailScreenState();
}

class _ScenarioDetailScreenState extends State<ScenarioDetailScreen> {
  late final ScenarioDetailCubit _cubit;

  @override
  void initState() {
    super.initState();
    _cubit = ScenarioDetailCubit()..loadDetail(widget.scenarioId);
  }

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

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
      value: _cubit,
      child: Scaffold(
        appBar: AppBar(title: const Text('Scenario Detail')),
        body: BlocBuilder<ScenarioDetailCubit, ScenarioDetailState>(
          builder: (context, state) {
            if (state is ScenarioDetailLoading) {
              return const Center(child: CircularProgressIndicator());
            }
            if (state is ScenarioDetailError) {
              return FSErrorState(
                message: state.message,
                onRetry: () => _cubit.loadDetail(widget.scenarioId),
              );
            }
            if (state is! ScenarioDetailLoaded) return const SizedBox.shrink();

            final s = state.scenario;
            return ListView(
              padding: AppSpacing.screenAll,
              children: [
                // Title
                Text(s.title, style: AppTextStyles.headlineMedium),
                AppSpacing.vSm,

                // Badges
                Wrap(
                  spacing: 6,
                  runSpacing: 6,
                  children: [
                    if (s.riskLevel != null) FSBadge.risk(s.riskLevel!),
                    if (s.difficulty != null)
                      FSBadge.difficulty(s.difficulty!),
                    if (s.eventType != null)
                      FSBadge(
                        text: s.eventType!,
                        variant: s.eventType!.toLowerCase() == 'major'
                            ? FSBadgeVariant.red
                            : FSBadgeVariant.blue,
                      ),
                    if (s.category != null)
                      FSBadge(text: s.category!, variant: FSBadgeVariant.purple),
                  ],
                ),
                AppSpacing.vLg,

                // Givens Table
                if (s.givensTable != null && s.givensTable!.isNotEmpty) ...[
                  Text('GIVEN DATA',
                      style: AppTextStyles.labelSmall.copyWith(
                          color: AppColors.textTertiary, letterSpacing: 1)),
                  AppSpacing.vSm,
                  GivensTableWidget(data: s.givensTable!),
                  AppSpacing.vLg,
                ],

                // Scenario Paragraph
                if (s.scenarioParagraph != null &&
                    s.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(
                      s.scenarioParagraph!,
                      style: AppTextStyles.bodyMedium.copyWith(height: 1.7),
                    ),
                  ),
                  AppSpacing.vLg,
                ],

                // Best Answer
                if (s.bestAnswer != null) ...[
                  _buildAnswerCard(
                    title: '✅ Best Answer',
                    answer: s.bestAnswer!,
                    rationale: s.bestAnswerRationale,
                    color: AppColors.success,
                    bgColor: AppColors.successBg,
                  ),
                  AppSpacing.vMd,
                ],

                // Other Options
                if (s.otherOption1 != null)
                  _buildAnswerCard(
                    title: 'Other Option',
                    answer: s.otherOption1!,
                    rationale: s.otherOption1Exp,
                    color: AppColors.textTertiary,
                    bgColor: AppColors.panel,
                  ),
                if (s.otherOption1 != null) AppSpacing.vSm,

                if (s.otherOption2 != null)
                  _buildAnswerCard(
                    title: 'Other Option',
                    answer: s.otherOption2!,
                    rationale: s.otherOption2Exp,
                    color: AppColors.textTertiary,
                    bgColor: AppColors.panel,
                  ),
                if (s.otherOption2 != null) AppSpacing.vSm,

                if (s.otherOption3 != null)
                  _buildAnswerCard(
                    title: 'Other Option',
                    answer: s.otherOption3!,
                    rationale: s.otherOption3Exp,
                    color: AppColors.textTertiary,
                    bgColor: AppColors.panel,
                  ),

                AppSpacing.vLg,

                // Timestamp
                if (s.createdAt != null)
                  Text(
                    'Created: ${Formatters.dateTime(s.createdAt)}',
                    style: AppTextStyles.caption,
                  ),
                AppSpacing.vXl,
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildAnswerCard({
    required String title,
    required String answer,
    String? rationale,
    required Color color,
    required Color bgColor,
  }) {
    return Container(
      padding: AppSpacing.cardInner,
      decoration: BoxDecoration(
        color: bgColor,
        border: Border.all(color: color.withOpacity(0.25)),
        borderRadius: AppRadius.smAll,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(title,
              style: AppTextStyles.labelSmall.copyWith(color: color)),
          const SizedBox(height: 6),
          Text(answer, style: AppTextStyles.bodyMedium),
          if (rationale != null && rationale.isNotEmpty) ...[
            const SizedBox(height: 8),
            Text(rationale,
                style: AppTextStyles.bodySmall
                    .copyWith(color: AppColors.textSecondary, height: 1.6)),
          ],
        ],
      ),
    );
  }
}