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/widgets/chat_bubble.dart';
import '../../../../core/widgets/rate_limit_timer.dart';
import '../../../../core/widgets/kb_selector.dart';
import '../bloc/chat_cubit.dart';
import '../bloc/chat_state.dart';

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

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  late final ChatCubit _cubit;
  final _inputCtrl = TextEditingController();
  final _scrollCtrl = ScrollController();

  @override
  void initState() {
    super.initState();
    _cubit = ChatCubit()..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.sendMessage(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(
        appBar: AppBar(
          title: const Text('AI Investment Advisor'),
          actions: [
            IconButton(
              icon: const Icon(Icons.delete_outline, size: 20),
              onPressed: () => _cubit.clearChat(),
              tooltip: 'Clear chat',
            ),
          ],
        ),
        body: Column(
          children: [
            // ── Messages ──
            Expanded(
              child: BlocConsumer<ChatCubit, ChatState>(
                listener: (_, __) => _scrollToBottom(),
                builder: (context, state) {
                  return ListView.builder(
                    controller: _scrollCtrl,
                    padding: const EdgeInsets.all(12),
                    itemCount: state.messages.length +
                        (state.isTyping ? 1 : 0) +
                        (state.isRateLimited ? 1 : 0),
                    itemBuilder: (context, index) {
                      // Rate limit timer at the end
                      if (state.isRateLimited &&
                          index ==
                              state.messages.length +
                                  (state.isTyping ? 1 : 0)) {
                        return Padding(
                          padding: const EdgeInsets.only(top: 8),
                          child: RateLimitTimer(
                            totalSeconds: state.rateLimitSeconds!,
                          ),
                        );
                      }

                      // Typing indicator
                      if (state.isTyping && index == state.messages.length) {
                        return const Padding(
                          padding: EdgeInsets.only(top: 8),
                          child: ChatBubble(text: '', isTyping: true),
                        );
                      }

                      final msg = state.messages[index];
                      return Padding(
                        padding: const EdgeInsets.only(top: 8),
                        child: ChatBubble(
                          text: msg.text,
                          isUser: msg.isUser,
                          ragUsed: msg.ragUsed,
                        ),
                      );
                    },
                  );
                },
              ),
            ),

            // ── Input Bar ──
            BlocBuilder<ChatCubit, ChatState>(
              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: [
                        // KB Selector
                        SizedBox(
                          width: 100,
                          child: KBSelector(
                            knowledgeBases: state.knowledgeBases,
                            selectedKB: state.selectedKbId,
                            onChanged: _cubit.selectKB,
                            compact: true,
                          ),
                        ),
                        const SizedBox(width: 8),
                        // Input
                        Expanded(
                          child: TextField(
                            controller: _inputCtrl,
                            enabled: !state.isTyping && !state.isRateLimited,
                            style: AppTextStyles.bodyMedium,
                            decoration: InputDecoration(
                              hintText: 'Ask about markets...',
                              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),
                        // Send
                        Material(
                          color: state.isTyping || state.isRateLimited
                              ? AppColors.accent.withOpacity(0.4)
                              : AppColors.accent,
                          borderRadius: AppRadius.smAll,
                          child: InkWell(
                            onTap: state.isTyping || state.isRateLimited
                                ? null
                                : _send,
                            borderRadius: AppRadius.smAll,
                            child: const SizedBox(
                              width: 44,
                              height: 44,
                              child: Icon(Icons.send_rounded,
                                  color: Colors.white, size: 20),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}