import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:provider/provider.dart';

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

  @override
  Widget build(BuildContext context) {
    return Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
      if (bookAppointmentsVM.isDoctorRatingDetailsLoading) {
        return Utils.getLoadingWidget();
      }

      final rating = bookAppointmentsVM.doctorsProfileResponseModel.decimalDoctorRate?.toDouble() ?? 0.0;
      if (rating == 0 || rating == 0.0) {
        return NoRatingDialog();
      }

      return DoctorRatingDialog(
        averageRating: rating,
        totalReviews: (bookAppointmentsVM.doctorsProfileResponseModel.noOfPatientsRate ?? 0).toInt(),
        fiveStarPercent: bookAppointmentsVM.doctorDetailsList.isNotEmpty ? bookAppointmentsVM.doctorDetailsList[0].ratio.round() : 0,
        fourStarPercent: bookAppointmentsVM.doctorDetailsList.length > 1 ? bookAppointmentsVM.doctorDetailsList[1].ratio.round() : 0,
        threeStarPercent: bookAppointmentsVM.doctorDetailsList.length > 2 ? bookAppointmentsVM.doctorDetailsList[2].ratio.round() : 0,
        twoStarPercent: bookAppointmentsVM.doctorDetailsList.length > 3 ? bookAppointmentsVM.doctorDetailsList[3].ratio.round() : 0,
        oneStarPercent: bookAppointmentsVM.doctorDetailsList.length > 4 ? bookAppointmentsVM.doctorDetailsList[4].ratio.round() : 0,
      );
    });
  }
}

class DoctorRatingDialog extends StatelessWidget {
  final double averageRating;
  final int totalReviews;
  final int fiveStarPercent;
  final int fourStarPercent;
  final int threeStarPercent;
  final int twoStarPercent;
  final int oneStarPercent;

  const DoctorRatingDialog({
    super.key,
    required this.averageRating,
    required this.totalReviews,
    required this.fiveStarPercent,
    required this.fourStarPercent,
    required this.threeStarPercent,
    required this.twoStarPercent,
    required this.oneStarPercent,
  });

  /// Returns the color for the rating badge and progress bar based on star level.
  /// 5 stars -> bright green
  /// 4 stars -> slightly darker green
  /// 3 stars -> dark yellow / olive
  /// 2 stars -> dark orange / brown-red
  /// 1 star  -> red
  Color _getBarColor(int stars) {
    switch (stars) {
      case 5:
        return AppColors.ratingFiveStarColor;
      case 4:
        return AppColors.ratingFourStarColor;
      case 3:
        return AppColors.ratingThreeStarColor;
      case 2:
        return AppColors.ratingTwoStarColor;
      case 1:
        return AppColors.ratingOneStarColor;
      default:
        return Colors.grey;
    }
  }

  /// Returns the background color for the large rating badge based on the
  /// overall average rating.
  Color _getBadgeColor(double rating) {
    if (rating == 0 || rating == 0.0) {
      return AppColors.greyLightColor; // Grey color for no rating
    } else if (rating >= 4.5) {
      return AppColors.ratingFiveStarColor; // Bright green
    } else if (rating >= 4.0) {
      return AppColors.ratingBadgeFiveStarColor; // Green
    } else if (rating >= 3.0) {
      return AppColors.ratingThreeStarColor;
    } else if (rating >= 2.0) {
      return AppColors.ratingTwoStarColor;
    } else {
      return AppColors.ratingOneStarColor;
    }
  }

  @override
  Widget build(BuildContext context) {
    final ratingRows = [
      _RatingRowData(stars: 5, percent: fiveStarPercent),
      _RatingRowData(stars: 4, percent: fourStarPercent),
      _RatingRowData(stars: 3, percent: threeStarPercent),
      _RatingRowData(stars: 2, percent: twoStarPercent),
      _RatingRowData(stars: 1, percent: oneStarPercent),
    ];

    return Container(
      width: 420,
      padding: const EdgeInsets.all(0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 130.w,
                height: 140.h,
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                  borderRadius: 16.r,
                  color: _getBadgeColor(averageRating),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      averageRating.toString(),
                      style: TextStyle(
                        fontFamily: "Poppins",
                        fontSize: 48.f,
                        fontWeight: FontWeight.w700,
                        color: averageRating == 0 || averageRating == 0.0 ? AppColors.textColor : AppColors.whiteColor,
                        height: 1.1,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 6,
                      ),
                      decoration: BoxDecoration(
                        color: averageRating == 0 || averageRating == 0.0 ? AppColors.greyF7Color : AppColors.textColor.withAlpha(20),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        children: [
                          NumberFormat.decimalPattern().format(totalReviews).toText12(
                            isBold: true,
                            color: averageRating == 0 || averageRating == 0.0 ? AppColors.textColor : AppColors.whiteColor,
                            isEnglishOnly: true
                          ),
                          ' ${LocaleKeys.reviews.tr(context: context)}'.toText12(
                            isBold: true,
                            color: averageRating == 0 || averageRating == 0.0 ? AppColors.textColor : AppColors.whiteColor,
                          ),
                        ],
                      ),
                      // child: Text(
                      //   '${NumberFormat.decimalPattern().format(totalReviews)} ${LocaleKeys.reviews.tr(context: context)}',
                      //   style: TextStyle(
                      //     fontSize: 12.f,
                      //     isBold: true,
                      //     color: averageRating == 0 || averageRating == 0.0 ? AppColors.textColor : AppColors.whiteColor,
                      //   ),
                      // ),
                    ).paddingSymmetrical(12.h, 0.h),
                  ],
                ),
              ),

              const SizedBox(width: 16),

              // ── Right: Star Breakdown ──
              Expanded(
                child: Column(
                  children: ratingRows
                      .map(
                        (row) => _buildRatingRow(row.stars, row.percent),
                      )
                      .toList(),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  Widget _buildRatingRow(int stars, int percent) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 5),
      child: Row(
        children: [
          // Star icons
          SizedBox(
            width: 70,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: List.generate(
                stars,
                (_) => Icon(Icons.star, size: 14, color: AppColors.ratingStarIconColor),
              ),
            ),
          ),

          const SizedBox(width: 8),
          Expanded(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child: SizedBox(
                height: 5.h,
                child: LinearProgressIndicator(
                  value: percent / 100,
                  backgroundColor: AppColors.shimmerBaseColor,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    _getBarColor(stars),
                  ),
                ),
              ),
            ),
          ),

          const SizedBox(width: 8),

          // Percentage text
          SizedBox(
            width: 36,
            child: Text(
              '$percent%',
              textAlign: TextAlign.right,
              style: TextStyle(
                fontFamily: "Poppins",
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: AppColors.ratingPercentageTextColor,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _RatingRowData {
  final int stars;
  final int percent;

  _RatingRowData({required this.stars, required this.percent});
}

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

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 420,
      padding: const EdgeInsets.all(24),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // Icon
          Container(
            width: 80,
            height: 80,
            decoration: BoxDecoration(
              color: AppColors.lightRedButtonColor,
              borderRadius: BorderRadius.circular(24),
            ),
            child: Icon(
              Icons.star_border_rounded,
              size: 48,
              color: AppColors.primaryRedColor,
            ),
          ),

          const SizedBox(height: 20),

          // Title
          Text(
            LocaleKeys.noRatingAvailable.tr(context: context),
            style: TextStyle(
              fontSize: 22,
              fontWeight: FontWeight.w700,
              color: AppColors.textColor,
            ),
            textAlign: TextAlign.center,
          ),

          const SizedBox(height: 12),

          // Description
          Text(
            LocaleKeys.doctorDoesNotHaveRating.tr(context: context),
            style: TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.w400,
              color: AppColors.textColorLight,
            ),
            textAlign: TextAlign.center,
          ),

          const SizedBox(height: 8),
        ],
      ),
    );
  }
}
