import 'package:cargocalculaterapp/core/extension/extension.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

import '../../utils/app_utils.dart';

typedef RatingChangeCallback = void Function(double rating)?;

const starPoints = 5;

class RatingBarWidget extends StatelessWidget {
  final double rating;
  final double iconsSize;
  final Color activeRatingColor;
  final Color inactiveRatingColor;
  final RatingChangeCallback onRatingChanged;
  final bool isAnimate;
  final Widget separator;
  final bool isSharp;

  const RatingBarWidget({
    super.key,
    required this.rating,
    this.iconsSize = 18,
    this.activeRatingColor = const Color(0xffFFA047),
    this.inactiveRatingColor = const Color(0xffCED5DF),
    this.onRatingChanged,
    this.isAnimate = false,
    this.separator = AppUtils.kBoxWidth3,
    this.isSharp = false,
  });

  @override
  Widget build(BuildContext context) {
    if (isAnimate) {
      return TweenAnimationBuilder<double>(
        duration: const Duration(milliseconds: 350),
        curve: Curves.easeInOut,
        tween: Tween<double>(begin: 0, end: rating),
        builder: (_, value, __) {
          return Row(
            mainAxisSize: MainAxisSize.min,
            children: List.generate(
              10,
              (index) => index.isEven
                  ? buildStar(index.exactIndex, rating, isSharp)
                  : separator,
            ),
          );
        },
      );
    }

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(
        10,
        (index) => index.isEven
            ? buildStar(index.exactIndex, rating, isSharp)
            : separator,
      ),
    );
  }

  Widget buildStar(int index, double rating, isSharp) {
    Widget icon;
    double present = rating - index;
    icon = ShaderMask(
      blendMode: BlendMode.srcIn,
      shaderCallback: (bounds) {
        return LinearGradient(
          tileMode: TileMode.clamp,
          colors: [activeRatingColor, inactiveRatingColor],
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
          stops: [present, present],
        ).createShader(bounds);
      },
      child: SvgPicture.asset(
        isSharp
            ? "assets/svg/ic_star_selected.svg"
            : "assets/svg/ic_star_selected.svg",
        height: iconsSize,
        width: iconsSize,
      ),
    );

    return InkResponse(
      onTap: onRatingChanged == null
          ? null
          : () => onRatingChanged!(index + 1.0),
      child: icon,
    );
  }
}
