import 'dart:math';

import 'package:design/design.dart';
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
import 'package:guru_utils/visual_feast/engine/visual_feast_engine.dart';
import 'package:guru_utils/visual_feast/visual_feast_animation.dart';
import 'package:guru_widgets/theme/guru_theme.dart';


class AssetText extends VisualFeastRender {
  final TextPainter comboPaint = TextPainter()
    ..textDirection = TextDirection.ltr
    ..textAlign = TextAlign.center;

  Offset textPosition = Offset.zero;

  final transaction = Vector2(0, 0);

  final Matrix4 matrix = Matrix4.identity();

  @override
  int get orderInLayer => 10;

  final int count;
  final Offset src = Offset(Get.size.width / 2, Get.size.height / 2);
  final Offset dst = Offset(Get.size.width / 2, Get.size.height / 2 - 40);

  AssetText(this.count) {
    setOpacity(0.0);
    refreshText();
  }

  @override
  void onAttach() {
    super.onAttach();
    fadeIn(src, dst);
  }

  @override
  void onDetach() {
    super.onDetach();
    engine.detachRenders([this]);
  }

  void refreshText({bool layout = true}) {
    comboPaint.text = TextSpan(
      text: "+$count",
      style: TextStyle(
          fontFamily: "EncodeSansExpanded",
          color: Colors.white.withOpacity(opacity),
          fontWeight: GuruTheme.fwExtraBold,
          fontSize: 24,
          shadows: [
            BoxShadow(
                color: Colors.black.withOpacity(min(opacity, 0.3)),
                offset: const Offset(0, 1),
                blurRadius: 2)
          ]),
    );
    comboPaint.layout();
    transaction.x = src.dx - comboPaint.width / 2.0;
  }

  void fadeIn(Offset src, Offset dst) {
    final fadeIn = VisualFeastAnimation(
        duration: const Duration(milliseconds: 750),
        delayed: const Duration(milliseconds: 300),
        from: src.dy,
        to: dst.dy,
        curve: Curves.easeOut,
        onUpdate: (value, percent, elapsed) {
          transaction.y = value;
          setOpacity((sin(percent * pi) * 1.3).clamp(0.0, 1.0));
        },
        onCompleted: () {
          setInvisible();
        });
    attachAnimation(fadeIn);
  }

  @override
  void onOpacityChanged(double opacity) {
    super.onOpacityChanged(opacity);
    refreshText(layout: false);
  }

  @override
  void onRender(Canvas canvas) {
    canvas.save();
    canvas.translate(transaction.x, transaction.y);
    comboPaint.paint(canvas, Offset.zero);
    canvas.restore();
  }

  @override
  String get renderId => "AssetText";
}
