import 'package:flutter/material.dart';
import 'formatted_text.dart';

class TypewriterText extends StatefulWidget {
  final String text;
  final TextStyle? style;
  final Duration charDelay;
  final VoidCallback? onComplete;

  const TypewriterText({
    super.key,
    required this.text,
    this.style,
    this.charDelay = const Duration(milliseconds: 20),
    this.onComplete,
  });

  @override
  State<TypewriterText> createState() => _TypewriterTextState();
}

class _TypewriterTextState extends State<TypewriterText> {
  String _displayed = '';
  int _index = 0;

  @override
  void initState() {
    super.initState();
    _typeNext();
  }

  @override
  void didUpdateWidget(TypewriterText old) {
    super.didUpdateWidget(old);
    if (old.text != widget.text) {
      _displayed = '';
      _index = 0;
      _typeNext();
    }
  }

  void _typeNext() {
    if (_index < widget.text.length) {
      Future.delayed(widget.charDelay, () {
        if (mounted) {
          setState(() {
            _displayed = widget.text.substring(0, _index + 1);
            _index++;
          });
          _typeNext();
        }
      });
    } else {
      widget.onComplete?.call();
    }
  }

  @override
  Widget build(BuildContext context) {
    final style = widget.style ?? DefaultTextStyle.of(context).style;
    return FormattedText(text: _displayed, baseStyle: style);
  }
}
