import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.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';

class MuridAndWhislist extends StatelessWidget {
  const MuridAndWhislist({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 Container(
      child: Row(
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.people_outline,
                color: Colors.white,
                size: getProportionateScreenWidth(22),
              ),
              SizedBox(width: getProportionateScreenWidth(4)),
              Text(
                ' ${dataDetailCourseModel.totalStudents} Murid',
                style: primaryTextStyle.copyWith(
                    fontSize: getProportionateScreenWidth(10),
                    letterSpacing: 0.5),
              )
            ],
          ),
          SizedBox(
            width: getProportionateScreenWidth(15),
          ),
          // Consumer<WishlistProvider>(builder: (context, state, _) {
          //   return Text(state.data.contains(dataDetailCourseModel.id)
          //       ? 'ada di wishlist'
          //       : 'ga ada');
          // }),
          GestureDetector(
            onTap: Provider.of<CartsProvider>(context)
                    .data
                    .contains(dataDetailCourseModel.id)
                ? checkUser
                : wishlistExist,
            child: !Condition.loginEmail
                ? Row(
                    children: [
                      Icon(
                        Icons.favorite_border,
                        color: Colors.white,
                        size: getProportionateScreenWidth(22),
                      ),
                      SizedBox(
                        width: getProportionateScreenWidth(4),
                      ),
                      Text(
                        'Tambah ke wishlist',
                        style: primaryTextStyle.copyWith(
                            fontSize: getProportionateScreenWidth(10),
                            letterSpacing: 0.2),
                      ),
                    ],
                  )
                : Row(
                    children: [
                      Consumer<wishlistProvider.WishlistProvider>(
                        builder: (context, state, _) {
                          if (state.state ==
                              wishlistProvider.ResultState.Loading) {
                            return Container(
                              height: 15,
                              width: 15,
                              child: CircularProgressIndicator(
                                color: secondaryColor,
                                strokeWidth: 1,
                              ),
                            );
                          }
                          return Icon(
                            state.data.contains(dataDetailCourseModel.id)
                                ? Icons.favorite_outlined
                                : Icons.favorite_border,
                            color: state.data.contains(dataDetailCourseModel.id)
                                ? Color(0xffCD2228)
                                : Colors.white,
                            size: getProportionateScreenWidth(22),
                          );
                        },
                      ),
                      SizedBox(
                        width: getProportionateScreenWidth(4),
                      ),
                      Consumer<wishlistProvider.WishlistProvider>(
                        builder: (contex, state, _) {
                          if (state.state ==
                              wishlistProvider.ResultState.Loading) {
                            return Text('');
                          }
                          return Text(
                            state.data.contains(dataDetailCourseModel.id)
                                ? 'Sudah dalam wihslist'
                                : 'Tambah ke wishlist',
                            style: primaryTextStyle.copyWith(
                                fontSize: getProportionateScreenWidth(10),
                                letterSpacing: 0.2),
                          );
                        },
                      ),
                    ],
                  ),
          )
        ],
      ),
    );
  }
}
