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/fs_button.dart';
import '../../../../core/widgets/fs_text_field.dart';
import '../../../../core/widgets/kb_selector.dart';
import '../bloc/generator_cubit.dart';
import '../bloc/generator_state.dart';

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

  @override
  State<GeneratorScreen> createState() => _GeneratorScreenState();
}

class _GeneratorScreenState extends State<GeneratorScreen> {
  late final GeneratorCubit _cubit;
  final _symbolCtrl = TextEditingController();
  final _windowCtrl = TextEditingController(text: '100');
  final _zMinCtrl = TextEditingController(text: '-2.5');
  final _zMaxCtrl = TextEditingController(text: '2.5');
  String? _selectedKb;

  @override
  void initState() {
    super.initState();
    _cubit = GeneratorCubit()..loadKnowledgeBases();
  }

  @override
  void dispose() {
    _symbolCtrl.dispose();
    _windowCtrl.dispose();
    _zMinCtrl.dispose();
    _zMaxCtrl.dispose();
    _cubit.close();
    super.dispose();
  }

  void _generate() {
    _cubit.generate(
      stockSymbol: _symbolCtrl.text.trim(),
      zscoreWindow: int.tryParse(_windowCtrl.text) ?? 100,
      zscoreTriggerMin: double.tryParse(_zMinCtrl.text) ?? -2.5,
      zscoreTriggerMax: double.tryParse(_zMaxCtrl.text) ?? 2.5,
      knowledgeBaseId: _selectedKb,
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
      value: _cubit,
      child: Scaffold(
        appBar: AppBar(title: const Text('Scenario Generator')),
        body: BlocConsumer<GeneratorCubit, GeneratorState>(
          listener: (context, state) {
            if (state is GeneratorSuccess) {
              context.push('/app/more/generator/results', extra: state.result);
            }
          },
          builder: (context, state) {
            final isRunning = state is GeneratorRunning;

            return ListView(
              padding: AppSpacing.screenAll,
              children: [
                Text('Generate investment scenarios from real market data.',
                    style: AppTextStyles.bodySmall),
                AppSpacing.vLg,

                // Config card
                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('Configuration', style: AppTextStyles.titleMedium),
                      AppSpacing.vMd,
                      FSTextField(
                        label: 'Stock Symbol',
                        hint: 'Leave empty for mixed basket (SPY, AAPL, TSLA...)',
                        controller: _symbolCtrl,
                        enabled: !isRunning,
                      ),
                      AppSpacing.vMd,
                      Row(
                        children: [
                          Expanded(
                            child: FSTextField(
                              label: 'Z-Score Min',
                              controller: _zMinCtrl,
                              keyboardType: const TextInputType.numberWithOptions(
                                  decimal: true, signed: true),
                              enabled: !isRunning,
                            ),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: FSTextField(
                              label: 'Z-Score Max',
                              controller: _zMaxCtrl,
                              keyboardType: const TextInputType.numberWithOptions(
                                  decimal: true, signed: true),
                              enabled: !isRunning,
                            ),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: FSTextField(
                              label: 'Window',
                              controller: _windowCtrl,
                              keyboardType: TextInputType.number,
                              enabled: !isRunning,
                            ),
                          ),
                        ],
                      ),
                      AppSpacing.vMd,
                      Text('STYLE KNOWLEDGE BASE',
                          style: AppTextStyles.labelSmall.copyWith(
                              color: AppColors.textSecondary,
                              letterSpacing: 1)),
                      const SizedBox(height: 6),
                      KBSelector(
                        knowledgeBases: _cubit.knowledgeBases,
                        selectedKB: _selectedKb,
                        onChanged: (v) => setState(() => _selectedKb = v),
                      ),
                    ],
                  ),
                ),
                AppSpacing.vLg,

                FSButton(
                  label: '⚡ Generate Scenarios',
                  isLoading: isRunning,
                  onPressed: isRunning ? null : _generate,
                  variant: FSButtonVariant.gradient,
                ),
                AppSpacing.vLg,

                // Status
                Container(
                  padding: AppSpacing.cardInner,
                  decoration: BoxDecoration(
                    color: AppColors.bgSecondary,
                    border: Border.all(color: AppColors.border),
                    borderRadius: AppRadius.smAll,
                  ),
                  child: _buildStatus(state),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildStatus(GeneratorState state) {
    if (state is GeneratorRunning) {
      return Row(
        children: [
          SizedBox(
            width: 16,
            height: 16,
            child: CircularProgressIndicator(
              strokeWidth: 2,
              valueColor:
                  AlwaysStoppedAnimation(AppColors.warning),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              '⏳ Fetching market data & running AI analysis...\nThis may take 15-30 seconds.',
              style: AppTextStyles.bodySmall
                  .copyWith(color: AppColors.warningLight),
            ),
          ),
        ],
      );
    }

    if (state is GeneratorError) {
      return Text(
        '❌ ${state.message}',
        style: AppTextStyles.bodySmall.copyWith(color: AppColors.errorLight),
      );
    }

    return Text(
      'Ready. Configure parameters and tap Generate.\n\n'
      'The pipeline will:\n'
      '1. Fetch 5 years of stock data (yfinance)\n'
      '2. Calculate rolling Z-Scores (Polars)\n'
      '3. Detect market anomalies\n'
      '4. Generate MCQ scenarios (Groq AI)\n'
      '5. Save to database',
      style: AppTextStyles.bodySmall.copyWith(
        color: AppColors.textTertiary,
        height: 1.6,
      ),
    );
  }
}