import 'package:cached_network_image/cached_network_image.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:initial_folder/base_service.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/detail_course_provider.dart'
    as detailCourseProv;
import 'package:initial_folder/providers/radeem_voucher_provider.dart';
import 'package:initial_folder/providers/whislist_provider.dart'
    as wishlistProvider;
import 'package:initial_folder/providers/whislist_provider.dart';
import 'package:initial_folder/providers/wishlist_post_provider.dart';
import 'package:initial_folder/screens/cart/cart_page.dart';
import 'package:initial_folder/screens/checkout/components/field_kupon.dart';
import 'package:initial_folder/screens/detail_course/components/murid_and_rating.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:initial_folder/widgets/login_regist/default_button.dart';
import 'package:initial_folder/widgets/login_regist/loading_button.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';

class HeaderCoupon extends StatelessWidget {
  const HeaderCoupon({
    Key? key,
    required this.dataDetailCourseModel,
  }) : super(key: key);

  final DataDetailCourseModel dataDetailCourseModel;

  @override
  Widget build(BuildContext context) {
    WishlistPostProvider wishlistPostProvider =
        Provider.of<WishlistPostProvider>(context);
    // var finalRating =
    //     double.parse((course.specificRating![0] / 20).toStringAsFixed(2));

    final kuponController = TextEditingController();
    bool isLoading = false;

    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 _showDialogNotLoginKupon() {
      return showDialog(
        context: context,
        builder: (context) => AlertDialog(
          contentPadding: EdgeInsets.fromLTRB(12, 20, 12, 1),
          content: Text(
            'Mohon login terlebih dahulu sebelum tukar kupon',
            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)),
            ),
          ],
        ),
      );
    }

    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();
      }
    }

    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();
      }
    }

    Future _showKupon() {
      return showDialog(
        context: context,
        builder: (context) => AlertDialog(
          contentPadding: EdgeInsets.fromLTRB(3, 1, 6, 30),
          content: SingleChildScrollView(
            child: Container(
              width: getProportionateScreenWidth(400),
              height: getProportionateScreenHeight(400),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      IconButton(
                        icon: Icon(Icons.cancel_rounded),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                    ],
                  ),
                  Center(
                    child: Column(
                      children: [
                        SizedBox(
                          height: getProportionateScreenHeight(30),
                        ),
                        Image.asset('assets/images/discount_coupon.png'),
                        SizedBox(
                          height: getProportionateScreenHeight(26),
                        ),
                        Text(
                          'Tukarkan Voucher',
                          style: thirdTextStyle.copyWith(
                              letterSpacing: 1,
                              fontWeight: semiBold,
                              fontSize: getProportionateScreenWidth(14)),
                        ),
                        SizedBox(
                          height: getProportionateScreenHeight(16),
                        ),
                        Text(
                          'Masukkan kode kupon untuk klaim\npromo menarik Vocasia',
                          textAlign: TextAlign.center,
                          style: primaryTextStyle.copyWith(
                              fontWeight: reguler,
                              fontSize: getProportionateScreenWidth(12)),
                        ),
                        SizedBox(
                          height: getProportionateScreenHeight(30),
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(
                              horizontal: getProportionateScreenWidth(16)),
                          child: FieldKupon(
                            controler: kuponController,
                          ),
                        ),
                        SizedBox(
                          height: getProportionateScreenHeight(7),
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(
                              horizontal: getProportionateScreenWidth(15)),
                          child: isLoading
                              ? LoadingButton(
                                  backgroundButtonColor: primaryColor,
                                  textButtonColor: Color(0xff050505),
                                )
                              : DefaultButton(
                                  text: 'Tukarkan',
                                  press: () async {
                                    final voucher = kuponController.text;
                                    if (await Provider.of<
                                                RadeemVoucherProvider>(context,
                                            listen: false)
                                        .radeemVoucher(
                                            int.parse(dataDetailCourseModel.id),
                                            voucher)) {
                                      await Provider.of<CartsProvider>(context,
                                              listen: false)
                                          .getCarts();
                                      Navigator.of(context).push(
                                        MaterialPageRoute(
                                          builder: (context) => CartPage(
                                            idcourse: dataDetailCourseModel.id,
                                            isiVoucher: voucher,
                                          ),
                                        ),
                                      );

                                      kuponController.clear();

                                      // _showMessage('Voucher Berhasil Digunakan');
                                    } else {
                                      ScaffoldMessenger.of(context)
                                          .showSnackBar(SnackBar(
                                        content: Text(
                                            "Kursus sudah di keranjang\natau kupon tidak valid"),
                                        duration: Duration(seconds: 4),
                                      ));
                                    }
                                  },
                                ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    }

    Widget imageCourse() {
      return Container(
        margin: EdgeInsets.only(
            left: getProportionateScreenWidth(2),
            right: getProportionateScreenWidth(2)),
        width: double.infinity,
        height: getProportionateScreenWidth(178),
        child: Column(
          children: [
            Container(
              width: double.infinity,
              height: getProportionateScreenWidth(178),
              child: CachedNetworkImage(
                imageUrl: dataDetailCourseModel.thumbnail ??
                    '$baseUrl/uploads/courses_thumbnail/course_thumbnail_default_57.jpg',
                imageBuilder: (context, imageProvider) => Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.vertical(
                        top: Radius.circular(5), bottom: Radius.circular(5)),
                    image: DecorationImage(
                      image: imageProvider,
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
                placeholder: (context, url) => Shimmer(
                    child: Container(
                      color: thirdColor,
                    ),
                    gradient: LinearGradient(
                        stops: [0.4, 0.5, 0.6],
                        colors: [secondaryColor, thirdColor, secondaryColor])),
                errorWidget: (context, url, error) => Icon(Icons.error),
              ),
            ),
          ],
        ),
      );
    }

    Widget buttonKuponWishlist() {
      return Row(
        children: [
          // Consumer<detailCourseProv.DetailCourseProvider>(
          //   builder: (context, state, _) {
          //     if (state.state == detailCourseProv.ResultState.HasData) {
          //       var detailCourse = state.result!.data[0][0];
          //       if (detailCourse.isFreeCourse == '1') {
          //         return SizedBox(width: 60);
          //       } else {
          //         return Container(
          //           margin:
          //               EdgeInsets.only(left: getProportionateScreenWidth(2)),
          //           child: ElevatedButton(
          //             style: ElevatedButton.styleFrom(
          //                 primary: Color(0xFF2D2D2D),
          //                 shape: RoundedRectangleBorder(
          //                     borderRadius: BorderRadius.circular(6))),
          //             onPressed: () {
          //               (Condition.loginEmail || Condition.loginFirebase)
          //                   ? _showKupon()
          //                   : _showDialogNotLoginKupon();
          //             },
          //             child: Padding(
          //               padding: EdgeInsets.symmetric(
          //                   horizontal: getProportionateScreenWidth(3),
          //                   vertical: getProportionateScreenHeight(6)),
          //               child: Row(
          //                 crossAxisAlignment: CrossAxisAlignment.center,
          //                 mainAxisAlignment: MainAxisAlignment.start,
          //                 children: [
          //                   Image.asset(
          //                     "assets/images/home_coupon.png",
          //                     color: Colors.white,
          //                   ),
          //                   SizedBox(
          //                     width: getProportionateScreenWidth(10),
          //                   ),
          //                   Text(
          //                     'Tukar Kupon',
          //                     textAlign: TextAlign.start,
          //                     style: thirdTextStyle.copyWith(
          //                         color: Colors.white,
          //                         fontSize: getProportionateScreenWidth(12),
          //                         fontWeight: reguler),
          //                   ),
          //                 ],
          //               ),
          //             ),
          //           ),
          //         );
          //       }
          //     } else {
          //       return Container();
          //     }
          //   },
          // ),

          SizedBox(width: 60),
          SizedBox(
            width: getProportionateScreenWidth(16),
          ),
          // Consumer<WishlistProvider>(builder: (context, state, _) {
          //   return Text(state.data.contains(dataDetailCourseModel.id)
          //       ? 'ada di wishlist'
          //       : 'ga ada');
          // }),
          Container(
            width: getProportionateScreenWidth(173),
            height: getProportionateScreenHeight(28),
            padding: EdgeInsets.symmetric(
                horizontal: getProportionateScreenWidth(12),
                vertical: getProportionateScreenHeight(6)),
            // color: Color(0xFF2D2D2D),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                color: Color(0xFF2D2D2D)),
            child: GestureDetector(
              onTap: Provider.of<CartsProvider>(context)
                      .data
                      .contains(dataDetailCourseModel.id)
                  ? checkUser
                  : wishlistExist,
              child: !Condition.loginEmail && !Condition.loginFirebase
                  ? Row(
                      children: [
                        Icon(
                          Icons.favorite_border,
                          color: Colors.white,
                          size: getProportionateScreenWidth(18),
                        ),
                        SizedBox(
                          width: getProportionateScreenWidth(6),
                        ),
                        Text(
                          'Tambah ke Wishlist',
                          style: primaryTextStyle.copyWith(
                              fontSize: getProportionateScreenWidth(12),
                              letterSpacing: 0.2),
                        ),
                      ],
                    )
                  : Row(
                      children: [
                        Consumer<wishlistProvider.WishlistProvider>(
                          builder: (context, state, _) {
                            if (state.state ==
                                wishlistProvider.ResultState.Loading) {
                              return Center(
                                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(18),
                            );
                          },
                        ),
                        SizedBox(
                          width: getProportionateScreenWidth(6),
                        ),
                        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(12),
                                  letterSpacing: 0.2),
                            );
                          },
                        ),
                      ],
                    ),
            ),
          ),
        ],
      );
    }

    return Container(
      margin: EdgeInsets.only(
          left: getProportionateScreenWidth(15),
          right: getProportionateScreenWidth(15)),
      width: SizeConfig.screenWidth,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: getProportionateScreenWidth(232),
            child: Text(dataDetailCourseModel.title ?? ' ',
                style: primaryTextStyle.copyWith(
                    letterSpacing: 0.1,
                    fontSize: getProportionateScreenHeight(14)),
                maxLines: 3,
                overflow: TextOverflow.ellipsis),
          ),
          SizedBox(
            height: getProportionateScreenHeight(13),
          ),
          // Row(
          //   // crossAxisAlignment: CrossAxisAlignment.start,
          //   children: [
          //     RatingBarIndicator(
          //         itemSize: getProportionateScreenWidth(10),
          //         rating: double.parse(
          //             dataDetailCourseModel.rating[0].avgRating != null
          //                 ? '${dataDetailCourseModel.rating[0].avgRating}'
          //                 : '5.0'),
          //         direction: Axis.horizontal,
          //         itemCount: 5,
          //         //itemPadding: EdgeInsets.symmetric(horizontal: 4.0),
          //         itemBuilder: (context, _) =>
          //             FaIcon(FontAwesomeIcons.solidStar, color: primaryColor)),
          //     SizedBox(
          //       width: getProportionateScreenWidth(4),
          //     ),
          //     Text(
          //       double.parse(dataDetailCourseModel.rating[0].avgRating != null
          //               ? '${dataDetailCourseModel.rating[0].avgRating}'
          //               : '5.0')
          //           .toString(),
          //       style: primaryTextStyle.copyWith(
          //           fontSize: getProportionateScreenWidth(10),
          //           color: secondaryColor,
          //           fontWeight: reguler),
          //     ),
          //     SizedBox(
          //       width: getProportionateScreenWidth(4),
          //     ),
          //     Text(
          //       // '(${course.numberOfRatings.toString()})',
          //       '(${dataDetailCourseModel.rating[0].totalReview})',
          //       style: primaryTextStyle.copyWith(
          //           fontSize: getProportionateScreenWidth(10),
          //           color: secondaryColor,
          //           fontWeight: reguler),
          //     ),
          //   ],
          // ),
          SizedBox(
            height: getProportionateScreenHeight(9),
          ),
          MuridAndRating(
            dataDetailCourseModel: dataDetailCourseModel,
          ),
          SizedBox(
            height: getProportionateScreenHeight(16),
          ),
          imageCourse(),
          SizedBox(
            height: getProportionateScreenHeight(11),
          ),
          // Consumer<detailCourseProv.DetailCourseProvider>(
          //   builder: (context, state, _) {
          //     if (state.state == detailCourseProv.ResultState.HasData) {
          //       var detailCourse = state.result!.data[0][0];
          //       if (detailCourse.isMine == 1) {
          //         return Container();
          //       } else {
          //         return buttonKuponWishlist();
          //       }
          //     } else {
          //       return Container();
          //     }
          //   },
          // ),
          buttonKuponWishlist(),
          SizedBox(
            height: getProportionateScreenHeight(11),
          ),
        ],
      ),
    );
  }
}
