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

/// Widget that renders streaming text with an animated cursor at the end,
/// giving the appearance of real-time text generation.
/// When streaming completes, renders Markdown.
class StreamTextWidget extends StatefulWidget {
  final String text;
  final bool isStreaming;
  final TextStyle? style;

  const StreamTextWidget({
    super.key,
    required this.text,
    this.isStreaming = true,
    this.style,
  });

  @override
  State<StreamTextWidget> createState() => _StreamTextWidgetState();
}

class _StreamTextWidgetState extends State<StreamTextWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController _cursorController;

  @override
  void initState() {
    super.initState();
    _cursorController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 600),
    )..repeat(reverse: true);
  }

  @override
  void dispose() {
    _cursorController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final defaultStyle = TextStyle(
      color: AppColors.textPrimary,
      fontSize: 15,
    );
    final effectiveStyle = widget.style ?? defaultStyle;

    // Streaming complete — render full Markdown
    if (!widget.isStreaming) {
      return MarkdownBody(
        data: widget.text,
        selectable: true,
        styleSheet: MarkdownStyleSheet(
          p: effectiveStyle,
          h1: effectiveStyle.copyWith(fontSize: 22, fontWeight: FontWeight.bold),
          h2: effectiveStyle.copyWith(fontSize: 19, fontWeight: FontWeight.bold),
          h3: effectiveStyle.copyWith(fontSize: 17, fontWeight: FontWeight.w600),
          strong: effectiveStyle.copyWith(fontWeight: FontWeight.bold),
          em: effectiveStyle.copyWith(fontStyle: FontStyle.italic, color: AppColors.textSecondary),
          code: TextStyle(
            color: AppColors.secondary,
            backgroundColor: AppColors.background.withOpacity(0.5),
            fontSize: 13,
            fontFamily: 'monospace',
          ),
          codeblockDecoration: BoxDecoration(
            color: AppColors.background.withOpacity(0.6),
            borderRadius: BorderRadius.circular(8),
          ),
          codeblockPadding: const EdgeInsets.all(10),
          tableBorder: TableBorder.all(color: AppColors.surfaceLight, width: 0.5),
          tableHead: effectiveStyle.copyWith(fontWeight: FontWeight.bold, fontSize: 13),
          tableBody: TextStyle(color: AppColors.textSecondary, fontSize: 13),
          tableCellsPadding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        ),
      );
    }

    // Still streaming — show plain text with blinking cursor
    return AnimatedBuilder(
      animation: _cursorController,
      builder: (context, _) {
        return RichText(
          text: TextSpan(
            style: effectiveStyle,
            children: [
              TextSpan(text: widget.text),
              TextSpan(
                text: '\u2588', // Block cursor character
                style: effectiveStyle.copyWith(
                  color: effectiveStyle.color?.withOpacity(
                    _cursorController.value,
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
