import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/models/detail_course_model.dart';
import 'package:initial_folder/providers/cart_provider.dart';
import 'package:initial_folder/providers/carts_provider.dart';
import 'package:initial_folder/providers/posting_review_provider.dart';
import 'package:initial_folder/providers/whislist_provider.dart'
    as wishlistProvider;
import 'package:initial_folder/providers/wishlist_post_provider.dart';
import 'package:initial_folder/screens/login/login_screen.dart';
import 'package:initial_folder/screens/login/login_with_email/login_email_screen.dart';
import 'package:initial_folder/screens/splash/splash_screen_login.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:provider/provider.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class MuridAndRating extends StatelessWidget {
  const MuridAndRating({Key? key, required this.dataDetailCourseModel})
      : super(key: key);
  final DataDetailCourseModel dataDetailCourseModel;
  @override
  Widget build(BuildContext context) {
    WishlistPostProvider wishlistPostProvider =
        Provider.of<WishlistPostProvider>(context);
    Future _showDialogNotLogin() {
      return showDialog(
        context: context,
        builder: (context) => AlertDialog(
          contentPadding: EdgeInsets.fromLTRB(12, 20, 12, 1),
          content: Text(
            'Mohon login terlebih dahulu sebelum menambahkan ke wishlist',
            style: primaryTextStyle.copyWith(
                fontSize: getProportionateScreenWidth(12), letterSpacing: 1),
          ),
          actions: [
            GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Text('Batal',
                  style: primaryTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(12),
                      letterSpacing: 1,
                      color: primaryColor)),
            ),
            SizedBox(
              width: getProportionateScreenWidth(5),
            ),
            GestureDetector(
              onTap: () => Navigator.of(context).pushNamedAndRemoveUntil(
                  LoginEmail.routeName, (Route<dynamic> route) => false),
              child: Text('Login',
                  style: primaryTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(12),
                      letterSpacing: 1,
                      color: primaryColor)),
            ),
          ],
        ),
      );
    }

    // Future _showMessage() {
    //   return showDialog(
    //     context: context,
    //     builder: (context) => AlertDialog(
    //       contentPadding: EdgeInsets.fromLTRB(22, 30, 22, 30),
    //       content: Text(
    //         'Berhasil menambahkan kursus ke wishlist',
    //         textAlign: TextAlign.center,
    //         style: primaryTextStyle.copyWith(
    //             fontSize: getProportionateScreenWidth(12), letterSpacing: 1),
    //       ),
    //     ),
    //   );
    // }

    addWishlist() async {
      var connectivityResult = await (Connectivity().checkConnectivity());
      if (connectivityResult == ConnectivityResult.none) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            duration: Duration(seconds: 1),
            backgroundColor: Colors.red[600],
            content: Text(
              'No Internet Connections',
              textAlign: TextAlign.center,
              style: primaryTextStyle.copyWith(color: Colors.white),
            ),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(5),
            ),
          ),
        );
      } else {
        await wishlistPostProvider
            .addWishlist(int.parse(dataDetailCourseModel.id));
        await Provider.of<wishlistProvider.WishlistProvider>(context,
                listen: false)
            .getWishlist();
        await Provider.of<CartProvider>(context, listen: false)
            .addCart(dataDetailCourseModel.id);
        await Provider.of<CartsProvider>(context, listen: false).getCarts();
      }
    }

    addWishlistNotExist() async {
      var connectivityResult = await (Connectivity().checkConnectivity());
      if (connectivityResult == ConnectivityResult.none) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            duration: Duration(seconds: 1),
            backgroundColor: Colors.red[600],
            content: Text(
              'No Internet Connections',
              textAlign: TextAlign.center,
              style: primaryTextStyle.copyWith(color: Colors.white),
            ),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(5),
            ),
          ),
        );
      } else {
        await wishlistPostProvider
            .addWishlist(int.parse(dataDetailCourseModel.id));
        await Provider.of<wishlistProvider.WishlistProvider>(context,
                listen: false)
            .getWishlist();
      }
    }

    // deleteWishlist() async {
    //   var connectivityResult = await (Connectivity().checkConnectivity());
    //   if (connectivityResult == ConnectivityResult.none) {
    //     ScaffoldMessenger.of(context).showSnackBar(
    //       SnackBar(
    //         duration: Duration(seconds: 1),
    //         backgroundColor: Colors.red[600],
    //         content: Text(
    //           'No Internet Connections',
    //           textAlign: TextAlign.center,
    //           style: primaryTextStyle.copyWith(color: Colors.white),
    //         ),
    //         behavior: SnackBarBehavior.floating,
    //         shape: RoundedRectangleBorder(
    //           borderRadius: BorderRadius.circular(5),
    //         ),
    //       ),
    //     );
    //   } else {
    //     await wishlistPostProvider
    //         .addWishlist(int.parse(dataDetailCourseModel.id));
    //   }
    // }

    checkUser() async {
      var token = await UsersInfo().getToken();
      if (token != null || Condition.loginFirebase == true) {
        addWishlist();
      } else {
        return _showDialogNotLogin();
      }
    }

    wishlistExist() async {
      var token = await UsersInfo().getToken();
      if (token != null || Condition.loginFirebase == true) {
        addWishlistNotExist();
      } else {
        return _showDialogNotLogin();
      }
    }

    return Padding(
      padding:
          EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(15)),
      child: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                SvgPicture.asset(
                  "assets/icons/student.svg",
                  width: getProportionateScreenWidth(17),
                  height: getProportionateScreenHeight(17),
                  color: Theme.of(context).brightness == Brightness.dark
                      ? baruTextutih
                      : fourthColor,
                ),
                SizedBox(width: getProportionateScreenWidth(4)),
                Text(
                  ' ${dataDetailCourseModel.totalStudents != null ? dataDetailCourseModel.totalStudents : "0"} Murid',
                  style: thirdTextStyle.copyWith(
                    fontSize: getProportionateScreenWidth(10),
                    fontWeight: medium,
                  ),
                )
              ],
            ),
            SizedBox(height: getProportionateScreenHeight(8)),
            Row(
              children: [
                dataDetailCourseModel.rating[0].avgRating != null &&
                    dataDetailCourseModel.rating[0].avgRating != 0
                ? Text(
                    double.parse('${dataDetailCourseModel.rating[0].avgRating}')
                        .toString(),
                    style: thirdTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(11),
                      fontWeight: medium,
                    ),
                  )
                : SizedBox.shrink(),

                SizedBox(width: getProportionateScreenWidth(4)),
                RatingBarIndicator(
                itemPadding: EdgeInsets.symmetric(
                    horizontal: getProportionateScreenWidth(2)),
                itemSize: getProportionateScreenWidth(13),
                rating: dataDetailCourseModel.rating[0].avgRating != null &&
                        dataDetailCourseModel.rating[0].avgRating != 0
                    ? double.parse('${dataDetailCourseModel.rating[0].avgRating}')
                    : 5.0, 
                direction: Axis.horizontal,
                itemCount: 5,
                itemBuilder: (context, _) => FaIcon(
                  FontAwesomeIcons.solidStar,
                  color: thirteenColor,
                ),
              ),
               if (dataDetailCourseModel.rating[0].totalReview != null &&
                  int.tryParse('${dataDetailCourseModel.rating[0].totalReview}') != null &&
                  int.parse('${dataDetailCourseModel.rating[0].totalReview}') > 0)
                ...[
                  SizedBox(width: getProportionateScreenWidth(4)),
                  Text(
                    '(${dataDetailCourseModel.rating[0].totalReview} Reviews)',
                    style: thirdTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(10),
                      fontWeight: medium,
                    ),
                  ),
                ]
              else
                SizedBox.shrink(),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
