import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import '../theme/app_colors.dart';
import '../theme/app_radius.dart';
import '../theme/app_text_styles.dart';

class ChatBubble extends StatelessWidget {
  final String text;
  final bool isUser;
  final bool isTyping;
  final bool isAkinator;
  final bool ragUsed;
  final Widget? bottomWidget;

  const ChatBubble({
    super.key,
    required this.text,
    this.isUser = false,
    this.isTyping = false,
    this.isAkinator = false,
    this.ragUsed = false,
    this.bottomWidget,
  });

  @override
  Widget build(BuildContext context) {
    final maxWidth = MediaQuery.of(context).size.width * 0.80;

    return Align(
      alignment: isUser ? Alignment.centerRight : Alignment.centerLeft,
      child: Container(
        constraints: BoxConstraints(maxWidth: maxWidth),
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
        decoration: BoxDecoration(
          color: isUser
              ? AppColors.accent
              : isAkinator
                  ? AppColors.panel.withOpacity(0.95)
                  : AppColors.panel,
          border: isUser
              ? null
              : Border.all(
                  color: isAkinator
                      ? AppColors.purple.withOpacity(0.2)
                      : AppColors.border,
                ),
          borderRadius: isUser ? AppRadius.bubbleUser : AppRadius.bubbleBot,
          gradient: isAkinator && !isUser
              ? LinearGradient(
                  colors: [AppColors.panel, AppColors.purple.withOpacity(0.06)],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                )
              : null,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (ragUsed && !isUser)
              Container(
                margin: const EdgeInsets.only(bottom: 8),
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                decoration: BoxDecoration(
                  color: AppColors.purpleBg,
                  borderRadius: AppRadius.pill,
                ),
                child: Text(
                  '🧠 RAG ACTIVATED',
                  style: TextStyle(
                    color: AppColors.purpleLight,
                    fontSize: 9,
                    fontWeight: FontWeight.w700,
                    letterSpacing: 0.5,
                  ),
                ),
              ),
            if (isTyping)
              _TypingIndicator()
            else if (isUser)
              Text(text, style: AppTextStyles.bodyMedium.copyWith(color: Colors.white))
            else
              MarkdownBody(
                data: text,
                selectable: true,
                styleSheet: _markdownStyle(),
              ),
            if (bottomWidget != null) ...[
              const SizedBox(height: 8),
              bottomWidget!,
            ],
          ],
        ),
      ),
    );
  }

  MarkdownStyleSheet _markdownStyle() {
    return MarkdownStyleSheet(
      p: AppTextStyles.bodyMedium.copyWith(height: 1.6),
      h1: AppTextStyles.titleLarge.copyWith(color: AppColors.accentLight),
      h2: AppTextStyles.titleMedium.copyWith(color: AppColors.accentLight),
      h3: AppTextStyles.titleSmall.copyWith(color: AppColors.accentLight),
      strong: AppTextStyles.bodyMedium.copyWith(fontWeight: FontWeight.w700),
      em: AppTextStyles.bodyMedium.copyWith(
        fontStyle: FontStyle.italic,
        color: AppColors.textSecondary,
      ),
      listBullet: AppTextStyles.bodyMedium,
      blockquoteDecoration: BoxDecoration(
        border: Border(left: BorderSide(color: AppColors.accent, width: 3)),
      ),
      blockquotePadding: const EdgeInsets.only(left: 12),
      code: AppTextStyles.monoSmall.copyWith(
        backgroundColor: AppColors.purpleBg,
      ),
      codeblockDecoration: BoxDecoration(
        color: AppColors.bgSecondary,
        border: Border.all(color: AppColors.border),
        borderRadius: AppRadius.smAll,
      ),
      tableBorder: TableBorder.all(color: AppColors.border, width: 0.5),
      tableHead: AppTextStyles.labelMedium.copyWith(color: AppColors.accentLight),
      tableBody: AppTextStyles.bodySmall,
      horizontalRuleDecoration: BoxDecoration(
        border: Border(top: BorderSide(color: AppColors.border)),
      ),
    );
  }
}

class _TypingIndicator extends StatefulWidget {
  @override
  State<_TypingIndicator> createState() => _TypingIndicatorState();
}

class _TypingIndicatorState extends State<_TypingIndicator>
    with TickerProviderStateMixin {
  late final List<AnimationController> _controllers;

  @override
  void initState() {
    super.initState();
    _controllers = List.generate(3, (i) {
      return AnimationController(
        vsync: this,
        duration: const Duration(milliseconds: 600),
      )..repeat(reverse: true);
    });
    for (var i = 0; i < 3; i++) {
      Future.delayed(Duration(milliseconds: i * 200), () {
        if (mounted) _controllers[i].forward();
      });
    }
  }

  @override
  void dispose() {
    for (final c in _controllers) {
      c.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(3, (i) {
        return AnimatedBuilder(
          animation: _controllers[i],
          builder: (_, __) {
            return Container(
              margin: const EdgeInsets.symmetric(horizontal: 2),
              width: 8,
              height: 8,
              decoration: BoxDecoration(
                color: AppColors.textTertiary.withOpacity(
                  0.3 + (_controllers[i].value * 0.7),
                ),
                shape: BoxShape.circle,
              ),
            );
          },
        );
      }),
    );
  }
}