import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../services/app_provider.dart';
import '../../services/api_service.dart';
import '../../widgets/glass_card.dart';
import '../../widgets/typewriter_text.dart';
import '../../widgets/formatted_text.dart';
import '../../widgets/ai_thinking_indicator.dart';
import '../../widgets/citation_chip.dart';
import '../../widgets/upgrade_prompt.dart';

class ChatScreen extends StatefulWidget {
  final String? conversationId;
  final String? initialMessage;
  const ChatScreen({super.key, this.conversationId, this.initialMessage});

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

class _ChatScreenState extends State<ChatScreen> {
  final _msgCtrl = TextEditingController();
  final _scrollCtrl = ScrollController();
  List<Map<String, dynamic>> _messages = [];
  bool _sending = false;
  bool _loading = true;
  String? _conversationId;
  int _lastNewAiIndex = -1;  // index of newest AI msg from this session

  static const _suggestions = [
    'What are my tenant rights?',
    'Explain breach of contract',
    'How do I write a cease and desist?',
    'What is the statute of limitations?',
  ];

  @override
  void initState() {
    super.initState();
    _conversationId = widget.conversationId;
    _loadMessages();
  }

  void _autoSendInitial() {
    if (widget.initialMessage != null && widget.initialMessage!.isNotEmpty) {
      _msgCtrl.text = widget.initialMessage!;
      _send();
    }
  }

  Future<void> _loadMessages() async {
    if (_conversationId == null) {
      setState(() => _loading = false);
      return;
    }
    try {
      final provider = context.read<AppProvider>();
      final res = await provider.api.getMessages(_conversationId!);
      setState(() {
        _messages = List<Map<String, dynamic>>.from(res['results'] ?? []);
        _loading = false;
      });
      _scrollToBottom();
      if (_messages.isEmpty) _autoSendInitial();
    } catch (_) {
      setState(() => _loading = false);
      _autoSendInitial();
    }
  }

  Future<void> _send() async {
    final text = _msgCtrl.text.trim();
    if (text.isEmpty || _sending) return;

    _msgCtrl.clear();
    setState(() {
      _messages.add({'role': 'user', 'content': text});
      _sending = true;
    });
    _scrollToBottom();

    try {
      final provider = context.read<AppProvider>();
      
      // Auto-create conversation if needed
      if (_conversationId == null) {
        final country = provider.auth.userCountry;
        final id = await provider.createConversation(
          title: text.length > 50 ? '${text.substring(0, 47)}...' : text,
          country: country,
        );
        setState(() => _conversationId = id);
      }
      
      final res = await provider.api.sendMessage(
        conversationId: _conversationId!,
        message: text,
      );
      final aiMsg = res['ai_message'] as Map<String, dynamic>?;
      final aiContent = aiMsg?['content']?.toString() ?? 'Sorry, no response received.';
      setState(() {
        _messages.add({...?aiMsg, 'role': 'assistant', 'content': aiContent});
        _lastNewAiIndex = _messages.length - 1;
        _sending = false;
      });
      _scrollToBottom();
    } on ApiException catch (e) {
      if (e.isLimitError) {
        setState(() => _sending = false);
        if (mounted) showUpgradePrompt(context, feature: 'AI queries');
      } else {
        setState(() {
          _messages.add({'role': 'assistant', 'content': 'Sorry, I encountered an error: ${e.message}'});
          _sending = false;
        });
      }
    } catch (_) {
      setState(() {
        _messages.add({'role': 'assistant', 'content': 'Connection error. Please try again.'});
        _sending = false;
      });
    }
  }

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(64),
        child: ClipRect(
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
            child: Container(
              padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
              decoration: BoxDecoration(
                color: AppColors.navy.withValues(alpha: 0.8),
                border: Border(bottom: BorderSide(color: AppColors.glassBorder)),
              ),
              child: Row(
                children: [
                  IconButton(
                    icon: const Icon(Icons.arrow_back_rounded, color: Colors.white),
                    onPressed: () => Navigator.of(context).pop(),
                  ),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('Reasonable Doubt AI', style: AppTypography.headingMd.copyWith(color: Colors.white)),
                      if (_sending)
                        Text('Thinking...', style: AppTypography.bodySm.copyWith(color: AppColors.gold)),
                    ],
                  ),
                  const Spacer(),
                  IconButton(
                    icon: const Icon(Icons.phone_rounded, color: AppColors.royalBlue),
                    onPressed: () => Navigator.of(context).pushNamed('/voice-call'),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: _loading
                ? const Center(child: CircularProgressIndicator(color: AppColors.royalBlue))
                : _messages.isEmpty && !_sending
                    ? _buildEmptyChat()
                    : ListView.builder(
                    controller: _scrollCtrl,
                    padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
                    itemCount: _messages.length + (_sending ? 1 : 0),
                    itemBuilder: (context, i) {
                      if (i == _messages.length && _sending) {
                        return Padding(
                          padding: const EdgeInsets.only(bottom: 16),
                          child: Row(
                            children: [
                              Container(
                                padding: const EdgeInsets.all(12),
                                decoration: BoxDecoration(
                                  color: AppColors.glassSurface,
                                  borderRadius: BorderRadius.circular(16),
                                  border: Border.all(color: AppColors.glassBorder),
                                ),
                                child: const AiThinkingIndicator(text: 'Analyzing...'),
                              ),
                            ],
                          ),
                        );
                      }
                      final msg = _messages[i];
                      final isUser = msg['role'] == 'user';
                      return _buildBubble(msg, isUser, i == _lastNewAiIndex && !isUser);
                    },
                  ),
          ),
          // Input area
          ClipRect(
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
              child: Container(
                padding: EdgeInsets.fromLTRB(16, 12, 16, MediaQuery.of(context).padding.bottom + 12),
                decoration: BoxDecoration(
                  color: AppColors.navy.withValues(alpha: 0.9),
                  border: Border(top: BorderSide(color: AppColors.glassBorder)),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                          color: AppColors.glassSurface,
                          borderRadius: BorderRadius.circular(22),
                          border: Border.all(color: AppColors.glassBorder),
                        ),
                        child: TextField(
                          controller: _msgCtrl,
                          style: AppTypography.bodyMd.copyWith(color: Colors.white),
                          maxLines: 4,
                          minLines: 1,
                          textInputAction: TextInputAction.send,
                          onSubmitted: (_) => _send(),
                          decoration: InputDecoration(
                            hintText: 'Type your question...',
                            hintStyle: AppTypography.bodyMd.copyWith(color: AppColors.textMuted),
                            border: InputBorder.none,
                            contentPadding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 10),
                    GestureDetector(
                      onTap: _send,
                      child: Container(
                        width: 44,
                        height: 44,
                        decoration: BoxDecoration(
                          gradient: LinearGradient(colors: [AppColors.royalBlue, AppColors.royalBlue.withValues(alpha: 0.8)]),
                          borderRadius: BorderRadius.circular(22),
                          boxShadow: [
                            BoxShadow(color: AppColors.royalBlue.withValues(alpha: 0.4), blurRadius: 12, offset: const Offset(0, 4)),
                          ],
                        ),
                        child: const Icon(Icons.send_rounded, color: Colors.white, size: 20),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBubble(Map<String, dynamic> msg, bool isUser, bool isLatest) {
    final content = msg['content']?.toString() ?? '';
    final messageId = msg['id']?.toString();
    
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: GestureDetector(
        onLongPress: () {
          Clipboard.setData(ClipboardData(text: content));
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: const Text('Message copied'),
              backgroundColor: AppColors.glassSurface,
              behavior: SnackBarBehavior.floating,
              duration: const Duration(seconds: 1),
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            ),
          );
        },
        child: Row(
        mainAxisAlignment: isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isUser)
            Container(
              width: 32,
              height: 32,
              margin: const EdgeInsets.only(right: 8, top: 4),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                gradient: LinearGradient(colors: [AppColors.royalBlue, AppColors.royalBlue.withValues(alpha: 0.6)]),
              ),
              child: const Icon(Icons.gavel_rounded, color: Colors.white, size: 16),
            ),
          Flexible(
            child: Column(
              crossAxisAlignment: isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start,
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  decoration: BoxDecoration(
                    color: isUser ? AppColors.royalBlue.withValues(alpha: 0.2) : AppColors.glassSurface,
                    borderRadius: BorderRadius.only(
                      topLeft: const Radius.circular(18),
                      topRight: const Radius.circular(18),
                      bottomLeft: Radius.circular(isUser ? 18 : 4),
                      bottomRight: Radius.circular(isUser ? 4 : 18),
                    ),
                    border: Border.all(
                      color: isUser ? AppColors.royalBlue.withValues(alpha: 0.3) : AppColors.glassBorder,
                    ),
                  ),
                  child: isLatest && !isUser
                      ? TypewriterText(
                          text: content,
                          style: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.5),
                        )
                      : isUser
                        ? Text(
                            content,
                            style: AppTypography.bodyMd.copyWith(
                              color: Colors.white,
                              height: 1.5,
                            ),
                          )
                        : FormattedText(
                            text: content,
                            baseStyle: AppTypography.bodyMd.copyWith(
                              color: Colors.white.withValues(alpha: 0.9),
                              height: 1.5,
                            ),
                          ),
                ),
                // Action buttons for assistant messages
                if (!isUser && messageId != null) ...[
                  const SizedBox(height: 6),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      _actionChip(Icons.bookmark_border_rounded, 'Save', () => _bookmarkMessage(messageId, content)),
                      const SizedBox(width: 8),
                      _actionChip(Icons.picture_as_pdf_rounded, 'PDF', () => _exportPdf(messageId)),
                      const SizedBox(width: 8),
                      _actionChip(Icons.copy_rounded, 'Copy', () {
                        Clipboard.setData(ClipboardData(text: content));
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: const Text('Copied to clipboard'),
                            backgroundColor: AppColors.glassSurface,
                            behavior: SnackBarBehavior.floating,
                            duration: const Duration(seconds: 1),
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                          ),
                        );
                      }),
                    ],
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
      ),
    );
  }
  
  Future<void> _bookmarkMessage(String messageId, String content) async {
    try {
      final provider = context.read<AppProvider>();
      await provider.addBookmark({
        'message': messageId,
        'note': content.length > 100 ? '${content.substring(0, 97)}...' : content,
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('Saved to bookmarks'),
            backgroundColor: AppColors.success,
            behavior: SnackBarBehavior.floating,
            duration: const Duration(seconds: 2),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(e.toString().contains('Already') ? 'Already bookmarked' : 'Failed to save'),
            backgroundColor: AppColors.error,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    }
  }

  Widget _actionChip(IconData icon, String label, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
        decoration: BoxDecoration(
          color: AppColors.glassSurface.withValues(alpha: 0.5),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: AppColors.glassBorder),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(icon, color: AppColors.textMuted, size: 14),
            const SizedBox(width: 4),
            Text(label, style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
          ],
        ),
      ),
    );
  }

  Future<void> _exportPdf(String messageId) async {
    try {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: const Text('Generating PDF...'),
          backgroundColor: AppColors.royalBlue,
          behavior: SnackBarBehavior.floating,
          duration: const Duration(seconds: 2),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        ),
      );
      final provider = context.read<AppProvider>();
      final pdfBytes = await provider.api.exportPdfBytes(messageId);
      final dir = await getTemporaryDirectory();
      final file = File('${dir.path}/reasonabledoubt_legal_opinion.pdf');
      await file.writeAsBytes(pdfBytes);
      if (mounted) {
        ScaffoldMessenger.of(context).clearSnackBars();
        final uri = Uri.file(file.path);
        if (await canLaunchUrl(uri)) {
          await launchUrl(uri);
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('PDF saved to ${file.path}'),
              backgroundColor: AppColors.success,
              behavior: SnackBarBehavior.floating,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            ),
          );
        }
      }
    } on ApiException catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).clearSnackBars();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('PDF export failed: ${e.message}'),
            backgroundColor: AppColors.error,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).clearSnackBars();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('Failed to export PDF'),
            backgroundColor: AppColors.error,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    }
  }

  Widget _buildEmptyChat() {
    return Center(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 64, height: 64,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: AppColors.royalBlue.withValues(alpha: 0.12),
              ),
              child: const Icon(Icons.gavel_rounded, color: AppColors.royalBlue, size: 30),
            ),
            const SizedBox(height: 16),
            Text('Ask me anything legal', style: AppTypography.headingMd.copyWith(color: Colors.white)),
            const SizedBox(height: 8),
            Text('I can help with rights, contracts, laws, and more',
                style: AppTypography.bodySm.copyWith(color: AppColors.textMuted), textAlign: TextAlign.center),
            const SizedBox(height: 24),
            Text('Try asking:', style: AppTypography.bodySm.copyWith(color: AppColors.textSecondary, fontWeight: FontWeight.w600)),
            const SizedBox(height: 12),
            ..._suggestions.map((s) => Padding(
              padding: const EdgeInsets.only(bottom: 8),
              child: GestureDetector(
                onTap: () {
                  _msgCtrl.text = s;
                  _send();
                },
                child: Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  decoration: BoxDecoration(
                    color: AppColors.glassSurface,
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: AppColors.glassBorder),
                  ),
                  child: Row(
                    children: [
                      const Icon(Icons.auto_awesome_rounded, color: AppColors.gold, size: 16),
                      const SizedBox(width: 10),
                      Expanded(child: Text(s, style: AppTypography.bodyMd.copyWith(color: Colors.white))),
                      const Icon(Icons.arrow_forward_ios_rounded, color: AppColors.textMuted, size: 14),
                    ],
                  ),
                ),
              ),
            )),
          ],
        ),
      ),
    );
  }
}
