import 'package:cs_resources/generated/assets.dart';
import 'package:flutter/material.dart';

import 'my_load_image.dart';

class MyLikeButton extends StatefulWidget {
  bool isLiked;
  bool isCustomIcon;
  final String? customIconActiveAssets;
  final String? customIconUnActiveAssets;
  double customIconWidth;
  double customIconHeight;
  final VoidCallback? onLike;
  final double size;
  final Color likedColor;
  final Color unlikedColor;
  final IconData activeIcon;
  final IconData unActiveIcon;

  MyLikeButton({
    Key? key,
    this.isLiked = false,
    this.isCustomIcon = false,
    this.customIconActiveAssets = Assets.communityLikeActive,
    this.customIconUnActiveAssets = Assets.communityLike,
    this.customIconWidth = 16.0,
    this.customIconHeight = 16.0,
    this.onLike,
    this.size = 24.0,
    this.likedColor = Colors.red,
    this.unlikedColor = Colors.grey,
    this.activeIcon = Icons.favorite,
    this.unActiveIcon = Icons.favorite_border,
  }) : super(key: key);

  @override
  MyLikeButtonState createState() => MyLikeButtonState();
}

class MyLikeButtonState extends State<MyLikeButton> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 150),
      vsync: this,
    );

    _scaleAnimation = Tween<double>(begin: 1.0, end: 1.2).animate(_controller)
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          _controller.reverse();
        }
      });
  }

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

  void _handleTap() {
    setState(() {
      widget.isLiked = !widget.isLiked;
    });
    _controller.forward(from: 0.0);
    widget.onLike?.call();
  }

  void triggerTap(){
    _handleTap();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleTap,
      child: AnimatedBuilder(
        animation: _scaleAnimation,
        builder: (context, child) {
          return Transform.scale(
            scale: _scaleAnimation.value,
            child: widget.isCustomIcon ?
              MyAssetImage(
                widget.isLiked ? widget.customIconActiveAssets??'': widget.customIconUnActiveAssets??'',
                width: widget.customIconWidth,
                height: widget.customIconHeight,
              ) : Icon(
              widget.isLiked ? widget.activeIcon : widget.unActiveIcon,
              size: widget.size,
              color: widget.isLiked ? widget.likedColor : widget.unlikedColor,
            ),
          );
        },
      ),
    );
  }
}