import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_box_decorations.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/features/rate_staff/domain/bloc/rating_staff_bloc.dart';

class RatingWidget extends StatelessWidget {
  const RatingWidget({super.key,});

  final double maxRating = 5.0; // Maximum rating, e.g., 5

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<RatingStaffBloc, RatingStaffState>(
      builder: (context, state) {
        return Container(
          padding: const EdgeInsets.all(12.0),
          margin: const EdgeInsets.only(left: 16, right: 16, top: 8),
          decoration: KwBoxDecorations.primaryLight12,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    'Client’s rate'.toUpperCase(),
                    style: AppTextStyles.captionReg
                        .copyWith(color: AppColors.blackCaptionText),
                  ),
                  state.rating >= 3
                      ? GestureDetector(
                          onTap: () {
                            BlocProvider.of<RatingStaffBloc>(context)
                                .add(StaffFavoriteToggleEvent());
                          },
                          child: state.favorite
                              ? Assets.images.icons.heart.svg()
                              : Assets.images.icons.heartEmpty.svg(),
                        )
                      : const SizedBox(height: 20)
                ],
              ),
              const Gap(4),
              Center(
                child: Text(state.rating.toStringAsFixed(1),
                    style: AppTextStyles.headingH0),
              ),
              const Gap(4),
              _buildRating(state.rating, context),
            ],
          ),
        );
      },
    );
  }

  _buildRating(int rating, BuildContext context) {
    List<Widget> stars = [];
    for (int i = 1; i <= maxRating; i++) {
      var star;
      if (i <= rating) {
        star = (Assets.images.icons.ratingStar.star.svg());
      } else {
        star = (Assets.images.icons.ratingStar.starEmpty.svg());
      }
      stars.add(GestureDetector(
        onTap: () {
          BlocProvider.of<RatingStaffBloc>(context).add(RatingChangedEvent(i));
        },
        child: star,
      ));
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [const Gap(28), ...stars, const Gap(28)],
    );
  }
}
