import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.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/scenario_card.dart';
import '../../../../core/widgets/fs_shimmer.dart';
import '../../../../core/widgets/fs_empty_state.dart';
import '../../../../core/widgets/fs_error_state.dart';
import '../bloc/scenario_cubit.dart';
import '../bloc/scenario_state.dart';

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

  @override
  State<ScenarioBrowserScreen> createState() => _ScenarioBrowserScreenState();
}

class _ScenarioBrowserScreenState extends State<ScenarioBrowserScreen> {
  late final ScenarioListCubit _cubit;
  final _scrollCtrl = ScrollController();

  @override
  void initState() {
    super.initState();
    _cubit = ScenarioListCubit()..loadScenarios();
    _scrollCtrl.addListener(_onScroll);
  }

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

  void _onScroll() {
    if (_scrollCtrl.position.pixels >=
        _scrollCtrl.position.maxScrollExtent - 200) {
      _cubit.loadMore();
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
      value: _cubit,
      child: Scaffold(
        appBar: AppBar(title: const Text('Scenarios')),
        body: BlocBuilder<ScenarioListCubit, ScenarioListState>(
          builder: (context, state) {
            return Column(
              children: [
                // Filter chips
                _buildFilterBar(state),

                // Content
                Expanded(
                  child: _buildContent(state),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildFilterBar(ScenarioListState state) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: [
          _filterChip(
            'All',
            state.difficultyFilter == null &&
                state.categoryFilter == null &&
                state.riskFilter == null,
            () => _cubit.clearFilters(),
          ),
          const SizedBox(width: 8),
          _filterChip('High Risk', state.riskFilter == 'High',
              () => _cubit.applyFilters(risk: 'High')),
          const SizedBox(width: 8),
          _filterChip('Medium Risk', state.riskFilter == 'Medium',
              () => _cubit.applyFilters(risk: 'Medium')),
          const SizedBox(width: 8),
          _filterChip('Low Risk', state.riskFilter == 'Low',
              () => _cubit.applyFilters(risk: 'Low')),
          const SizedBox(width: 8),
          _filterChip('Easy', state.difficultyFilter == 'easy',
              () => _cubit.applyFilters(difficulty: 'easy')),
          const SizedBox(width: 8),
          _filterChip('Medium', state.difficultyFilter == 'medium',
              () => _cubit.applyFilters(difficulty: 'medium')),
          const SizedBox(width: 8),
          _filterChip('Hard', state.difficultyFilter == 'hard',
              () => _cubit.applyFilters(difficulty: 'hard')),
        ],
      ),
    );
  }

  Widget _filterChip(String label, bool selected, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      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 _buildContent(ScenarioListState state) {
    if (state.isLoading) {
      return ListView.builder(
        padding: AppSpacing.screenH,
        itemCount: 6,
        itemBuilder: (_, __) => Padding(
          padding: const EdgeInsets.only(bottom: 12),
          child: FSShimmer.card(height: 100),
        ),
      );
    }

    if (state.error != null && state.scenarios.isEmpty) {
      return FSErrorState(
        message: state.error!,
        onRetry: () => _cubit.loadScenarios(),
      );
    }

    if (state.scenarios.isEmpty) {
      return const FSEmptyState(
        icon: '📚',
        title: 'No scenarios found',
        subtitle: 'Generate some first using the Scenario Generator!',
      );
    }

    return RefreshIndicator(
      color: AppColors.accent,
      backgroundColor: AppColors.panel,
      onRefresh: () => _cubit.loadScenarios(),
      child: ListView.builder(
        controller: _scrollCtrl,
        padding: AppSpacing.screenH,
        itemCount: state.scenarios.length + (state.isLoadingMore ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == state.scenarios.length) {
            return const Padding(
              padding: EdgeInsets.all(16),
              child: Center(child: CircularProgressIndicator()),
            );
          }

          final s = state.scenarios[index];
          return Padding(
            padding: const EdgeInsets.only(bottom: 10),
            child: ScenarioCard(
              title: s.title,
              description: s.shortDescription,
              riskLevel: s.riskLevel,
              difficulty: s.difficulty,
              eventType: s.eventType,
              onTap: () => context.push('/app/more/scenarios/${s.id}'),
            ),
          );
        },
      ),
    );
  }
}