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_radius.dart';
import '../../../../core/theme/app_gradients.dart';
import '../../../../core/widgets/rate_limit_timer.dart';
import '../../../../core/widgets/kb_selector.dart';
import '../bloc/akinator_cubit.dart';
import '../bloc/akinator_state.dart';
import '../widgets/akinator_banner.dart';
import '../widgets/akinator_message_card.dart';
import '../widgets/panel_mode_toggle.dart';

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

  @override
  State<AkinatorScreen> createState() => _AkinatorScreenState();
}

class _AkinatorScreenState extends State<AkinatorScreen> {
  late final AkinatorCubit _cubit;
  final _inputCtrl = TextEditingController();
  final _scrollCtrl = ScrollController();

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

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

  void _send() {
    final text = _inputCtrl.text.trim();
    if (text.isEmpty) return;
    _inputCtrl.clear();
    _cubit.sendQuery(text);
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollCtrl.hasClients) {
        _scrollCtrl.animateTo(
          _scrollCtrl.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
      value: _cubit,
      child: Scaffold(
        body: SafeArea(
          child: Column(
            children: [
              const AkinatorBanner(),
              BlocBuilder<AkinatorCubit, AkinatorState>(
                buildWhen: (p, c) => p.panelMode != c.panelMode,
                builder: (_, state) => PanelModeToggle(
                  isOn: state.panelMode,
                  onChanged: (_) => _cubit.togglePanelMode(),
                ),
              ),

              // ── Messages ──
              Expanded(
                child: BlocConsumer<AkinatorCubit, AkinatorState>(
                  listener: (_, __) => _scrollToBottom(),
                  builder: (context, state) {
                    final itemCount = state.messages.length +
                        (state.isTyping ? 1 : 0) +
                        (state.isRateLimited ? 1 : 0);

                    return Container(
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            AppColors.purple.withOpacity(0.03),
                            AppColors.bg,
                          ],
                        ),
                      ),
                      child: ListView.builder(
                        controller: _scrollCtrl,
                        padding: const EdgeInsets.all(12),
                        itemCount: itemCount,
                        itemBuilder: (context, index) {
                          if (state.isRateLimited &&
                              index ==
                                  state.messages.length +
                                      (state.isTyping ? 1 : 0)) {
                            return Padding(
                              padding: const EdgeInsets.only(top: 8),
                              child: RateLimitTimer(
                                totalSeconds: state.rateLimitSeconds!,
                              ),
                            );
                          }

                          if (state.isTyping &&
                              index == state.messages.length) {
                            return Padding(
                              padding: const EdgeInsets.only(top: 8),
                              child: Align(
                                alignment: Alignment.centerLeft,
                                child: Container(
                                  constraints: BoxConstraints(
                                    maxWidth:
                                        MediaQuery.of(context).size.width *
                                            0.80,
                                  ),
                                  padding: const EdgeInsets.all(12),
                                  decoration: BoxDecoration(
                                    color: AppColors.panel,
                                    border: Border.all(
                                        color: AppColors.purple
                                            .withOpacity(0.2)),
                                    borderRadius: AppRadius.bubbleBot,
                                  ),
                                  child: Text(
                                    state.panelMode
                                        ? '🎭 Running panel debate with 10 investor personas... 30-60s'
                                        : '🔮 Running 9-node pipeline with 5 analyst tools... 15-30s',
                                    style: AppTextStyles.bodySmall.copyWith(
                                      color: AppColors.purpleLight,
                                      fontStyle: FontStyle.italic,
                                    ),
                                  ),
                                ),
                              ),
                            );
                          }

                          return Padding(
                            padding: const EdgeInsets.only(top: 10),
                            child: AkinatorMessageCard(
                                message: state.messages[index]),
                          );
                        },
                      ),
                    );
                  },
                ),
              ),

              // ── Input Bar ──
              BlocBuilder<AkinatorCubit, AkinatorState>(
                builder: (context, state) {
                  return Container(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 12, vertical: 8),
                    decoration: const BoxDecoration(
                      color: AppColors.panel,
                      border:
                          Border(top: BorderSide(color: AppColors.border)),
                    ),
                    child: SafeArea(
                      top: false,
                      child: Row(
                        children: [
                          SizedBox(
                            width: 100,
                            child: KBSelector(
                              knowledgeBases: state.knowledgeBases,
                              selectedKB: state.selectedKbId,
                              onChanged: _cubit.selectKB,
                              compact: true,
                            ),
                          ),
                          const SizedBox(width: 8),
                          Expanded(
                            child: TextField(
                              controller: _inputCtrl,
                              enabled:
                                  !state.isTyping && !state.isRateLimited,
                              style: AppTextStyles.bodyMedium,
                              decoration: InputDecoration(
                                hintText: 'Ask Akinator about any investment...',
                                contentPadding: const EdgeInsets.symmetric(
                                    horizontal: 14, vertical: 10),
                                border: OutlineInputBorder(
                                  borderRadius: AppRadius.smAll,
                                  borderSide: BorderSide.none,
                                ),
                                filled: true,
                                fillColor: AppColors.bgSecondary,
                              ),
                              onSubmitted: (_) => _send(),
                            ),
                          ),
                          const SizedBox(width: 8),
                          DecoratedBox(
                            decoration: BoxDecoration(
                              gradient:
                                  state.isTyping || state.isRateLimited
                                      ? null
                                      : AppGradients.akinatorButton,
                              color: state.isTyping || state.isRateLimited
                                  ? AppColors.purple.withOpacity(0.3)
                                  : null,
                              borderRadius: AppRadius.smAll,
                            ),
                            child: Material(
                              color: Colors.transparent,
                              child: InkWell(
                                onTap:
                                    state.isTyping || state.isRateLimited
                                        ? null
                                        : _send,
                                borderRadius: AppRadius.smAll,
                                child: const SizedBox(
                                  width: 44,
                                  height: 44,
                                  child: Center(
                                    child: Text('🔮',
                                        style: TextStyle(fontSize: 20)),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}