import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/helper/validator.dart';

import 'package:initial_folder/providers/cart_provider.dart' as cartProvider;
import 'package:initial_folder/providers/carts_provider.dart' as cartsProvider;
import 'package:initial_folder/providers/detail_course_coupon_provider.dart';

import 'package:initial_folder/providers/detail_rating_course_provider.dart'
    as detailRatingCourseProvider;
import 'package:initial_folder/providers/instructor_provider.dart'
    as instructorProvider;
import 'package:initial_folder/providers/lesson_course_provider.dart'
    as lessonCourseProvider;
import 'package:initial_folder/providers/my_course_provider.dart'
    as myCourseProvider;
import 'package:initial_folder/providers/order_provider.dart' as orderProvider;
import 'package:initial_folder/providers/payments_provider.dart'
    as paymentsProvider;
import 'package:initial_folder/providers/section_lesson_course_provider.dart'
    as sectionLessonCourseProvider;
import 'package:initial_folder/providers/tab_provider.dart';
import 'package:initial_folder/providers/total_price_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/cart/cart_page.dart';
import 'package:initial_folder/screens/checkout/checkout_coupon_page.dart';
import 'package:initial_folder/screens/checkout/checkout_page.dart';
import 'package:initial_folder/screens/course/play_course_page.dart';
import 'package:initial_folder/screens/detail_course/components/header_coupon.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/my_course/success_free_course.dart';
import 'package:initial_folder/screens/splash/splash_screen_login.dart';
import 'package:initial_folder/screens/detail_course/components/app_bar.dart';
import 'package:initial_folder/screens/detail_course/components/custom_tab_bar.dart';
import 'package:initial_folder/screens/detail_course/components/header.dart';
import 'package:initial_folder/services/course_service.dart';
import 'package:initial_folder/services/instructor_service.dart';
import 'package:initial_folder/services/lesson_course_service.dart';
import 'package:initial_folder/services/section_lesson_service.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:provider/provider.dart';

class DetailCourseCouponScreen extends StatelessWidget {
  const DetailCourseCouponScreen(
      {Key? key, required this.idcourse, required this.coupon})
      : super(key: key);
  final String idcourse;
  final String coupon;

  static String routeName = "/course_detail";
  @override
  Widget build(BuildContext context) {
    final typeCoupon = Provider.of<TotalPriceProvider>(context).typeCoupon;
    final selected = Provider.of<TotalPriceProvider>(context);
    // Provider.of<orderProvider.OrderProvider>(context).clearOrder();
    // Provider.of<orderProvider.OrderProvider>(context).clearInvoice();
    paymentsProvider.PaymentsProvider pay =
        Provider.of<paymentsProvider.PaymentsProvider>(context);
    SizeConfig().init(context);
    showNotifDialog(BuildContext context) {
      showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            content: Consumer<paymentsProvider.PaymentsProvider>(
              builder: (context, state, child) {
                if (state.state == paymentsProvider.ResultState.gagal) {
                  return Container(
                    height: getProportionateScreenHeight(40),
                    width: getProportionateScreenWidth(15),
                    child: Center(
                      child: Text(
                        'Anda sudah memiliki kursus ini',
                        style: primaryTextStyle.copyWith(fontSize: 12),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  );
                } else {
                  return Text(
                    'Erorr lain',
                    style: thirdTextStyle,
                  );
                }
              },
            ),
          );
        },
        // barrierDismissible: false,
      );
    }

    Future _showDialogNotLogin(String teks) {
      return showDialog(
        context: context,
        builder: (context) => AlertDialog(
          contentPadding: EdgeInsets.fromLTRB(12, 20, 12, 1),
          content: Text(
            'Mohon login terlebih dahulu sebelum $teks',
            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<void> _showMessage() {
      return showModalBottomSheet<void>(
        context: context,
        builder: (BuildContext context) {
          return Consumer<cartProvider.CartProvider>(
              builder: (context, state, _) {
            if (state.state == cartProvider.ResultState.loading) {
              return Container(
                  decoration: BoxDecoration(
                    boxShadow: [
                      BoxShadow(
                        blurRadius: 10,
                        offset: Offset(0, -1),
                      )
                    ],
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(10),
                    ),
                    color: Color(0xff242424),
                  ),
                  height: getProportionateScreenHeight(200),
                  child: Center(
                    child: CircularProgressIndicator(
                      strokeWidth: 1,
                      color: primaryColor,
                    ),
                  ));
            } else if (state.state == cartProvider.ResultState.succes) {
              return Container(
                decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                      blurRadius: 10,
                      offset: Offset(0, -1),
                    )
                  ],
                  borderRadius: BorderRadius.vertical(
                    top: Radius.circular(10),
                  ),
                  color: Color(0xff242424),
                ),
                height: getProportionateScreenHeight(200),
                child: Column(
                  children: [
                    Row(
                      children: [
                        IconButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            icon: Icon(
                              Icons.close,
                              color: secondaryColor,
                              size: 15,
                            )),
                      ],
                    ),
                    Icon(
                      Icons.check_rounded,
                      size: 40,
                      color: eightColor,
                    ),
                    SizedBox(
                      height: getProportionateScreenWidth(15),
                    ),
                    Text(
                      'Berhasil menambahkan kursus ke keranjang',
                      textAlign: TextAlign.center,
                      style: primaryTextStyle.copyWith(
                          fontSize: SizeConfig.blockHorizontal! * 4,
                          letterSpacing: 0.5),
                    ),
                    SizedBox(
                      height: getProportionateScreenWidth(4),
                    ),
                    TextButton(
                      style: ButtonStyle(
                        overlayColor: MaterialStateProperty.all(sixColor),
                        padding: MaterialStateProperty.all(
                          EdgeInsets.symmetric(vertical: 1, horizontal: 1),
                        ),
                      ),
                      onPressed: () {
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (context) => CartPage(
                                  idcourse: idcourse,
                                )));
                      },
                      child: Text(
                        'Lihat keranjang',
                        style: thirdTextStyle.copyWith(
                            fontSize: getProportionateScreenWidth(13),
                            letterSpacing: 0.5,
                            color: primaryColor),
                      ),
                    ),
                  ],
                ),
              );
            } else if (state.state == cartProvider.ResultState.failed) {
              return Container(
                decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                      blurRadius: 10,
                      offset: Offset(0, -1),
                    )
                  ],
                  borderRadius: BorderRadius.vertical(
                    top: Radius.circular(10),
                  ),
                  color: Color(0xff242424),
                ),
                height: getProportionateScreenHeight(200),
                child: Column(
                  children: [
                    Row(
                      children: [
                        IconButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            icon: Icon(
                              Icons.close,
                              color: secondaryColor,
                              size: 15,
                            )),
                      ],
                    ),
                    Icon(
                      Icons.check_rounded,
                      size: 40,
                      color: eightColor,
                    ),
                    SizedBox(
                      height: getProportionateScreenWidth(15),
                    ),
                    Text(
                      'Berhasil menghapus kursus dari keranjang',
                      textAlign: TextAlign.center,
                      style: primaryTextStyle.copyWith(
                          fontSize: SizeConfig.blockHorizontal! * 4,
                          letterSpacing: 0.5),
                    ),
                    SizedBox(
                      height: getProportionateScreenWidth(4),
                    ),
                    TextButton(
                      style: ButtonStyle(
                        overlayColor: MaterialStateProperty.all(sixColor),
                        padding: MaterialStateProperty.all(
                          EdgeInsets.symmetric(vertical: 1, horizontal: 1),
                        ),
                      ),
                      onPressed: () {
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (context) => CartPage(
                                  idcourse: idcourse,
                                )));
                      },
                      child: Text(
                        'Lihat keranjang',
                        style: thirdTextStyle.copyWith(
                            fontSize: getProportionateScreenWidth(13),
                            letterSpacing: 0.5,
                            color: primaryColor),
                      ),
                    ),
                  ],
                ),
              );
            } else {
              return Container(
                  decoration: BoxDecoration(
                    boxShadow: [
                      BoxShadow(
                        blurRadius: 10,
                        offset: Offset(0, -1),
                      )
                    ],
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(10),
                    ),
                    color: Color(0xff242424),
                  ),
                  height: getProportionateScreenHeight(200),
                  child: Center(
                    child: Text('Terjadi Kesalahan'),
                  ));
            }
          });
        },
      );
    }

    handleNotLogin() async {
      var token = await UsersInfo().getToken();
      if (token != null || Condition.loginFirebase == true) {
        _showMessage();
        await Provider.of<cartProvider.CartProvider>(context, listen: false)
            .addCart(int.parse(idcourse));
        await Provider.of<cartsProvider.CartsProvider>(context, listen: false)
            .getCarts();
        await Provider.of<WishlistPostProvider>(context, listen: false)
            .addWishlist(int.parse(idcourse));
        await Provider.of<wishlistProvider.WishlistProvider>(context,
                listen: false)
            .getWishlist();
        // cartsDatabaseProvider.setCarts(id);
      } else {
        String teks = 'menambahkan ke keranjang';
        return _showDialogNotLogin(teks);
      }
    }

    handleNotLoginWishlistNotExist() async {
      var token = await UsersInfo().getToken();
      if (token != null || Condition.loginFirebase == true) {
        _showMessage();
        await Provider.of<cartProvider.CartProvider>(context, listen: false)
            .addCart(int.parse(idcourse));
        await Provider.of<cartsProvider.CartsProvider>(context, listen: false)
            .getCarts();
      } else {
        String teks = 'menambahkan ke keranjang';
        return _showDialogNotLogin(teks);
      }
    }

    handleNotLoginBuy(
        {required String title,
        required String price,
        required String discountPrice,
        required String instructor,
        required String imageUrl}) async {
      var token = await UsersInfo().getToken();
      if (token != null || Condition.loginFirebase == true) {
        Provider.of<orderProvider.OrderProvider>(context, listen: false)
            .clear();
        Provider.of<orderProvider.OrderProvider>(context, listen: false)
            .addOrder(
          id: idcourse,
          title: title,
          price: price,
          discountPrice: discountPrice,
          imageUrl: imageUrl,
          instructor: instructor,
        );
        Provider.of<orderProvider.OrderProvider>(context, listen: false)
            .getTotalPrice(discountPrice);
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => CheckoutCouponPage(
                  discountPrice: discountPrice,
                  idCourse: idcourse,
                  instructor: instructor,
                  title: title,
                  price: price,
                  coupon: coupon,
                )));
      } else {
        String teks = 'membeli kursus';
        return _showDialogNotLogin(teks);
      }
    }

    handleNotLoginFree(
      String? id,
      String? title,
      String? thumb,
      String? instr,
    ) async {
      var token = await UsersInfo().getToken();
      if (token != null || Condition.loginFirebase == true) {
        if (await pay.freeCourse(int.parse(idcourse))) {
          await Provider.of<myCourseProvider.MyCourseProvider>(context,
                  listen: false)
              .getMyCourse();
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => SuccessFreeCourse(
                        id: id,
                        thumbnail: thumb,
                        title: title,
                        instructor: instr,
                      )));
        } else {
          showNotifDialog(context);
        }
      } else {
        String teks = 'memiliki kursus ini';
        return _showDialogNotLogin(teks);
      }
    }

    Widget freeBottomNav(String? courseId, String? instructor,
        String? thumbnail, String? title) {
      return Container(
        width: double.infinity,
        height: getProportionateScreenHeight(60),
        decoration: BoxDecoration(
            border:
                Border.symmetric(horizontal: BorderSide(color: fourthColor)),
            boxShadow: [
              BoxShadow(
                  offset: Offset(0, -2),
                  blurRadius: 50,
                  color: fourthColor.withOpacity(0.15))
            ]),
        child: Row(
          children: [
            SizedBox(
              width: 13,
            ),
            Text(
              'Gratis',
              style: primaryTextStyle.copyWith(
                  fontSize: getProportionateScreenHeight(20),
                  letterSpacing: 0.23),
            ),
            Spacer(),
            GestureDetector(
              onTap: () =>
                  handleNotLoginFree(courseId, title, thumbnail, instructor),
              child: Container(
                margin: EdgeInsets.only(right: getProportionateScreenWidth(15)),
                width: getProportionateScreenWidth(123),
                height: getProportionateScreenHeight(33),
                decoration: BoxDecoration(
                    color: primaryColor,
                    borderRadius: BorderRadius.circular(5)),
                child: Center(
                  child: Consumer<paymentsProvider.PaymentsProvider>(
                      builder: (context, state, _) {
                    if (state.stateProcess ==
                        paymentsProvider.Process.uninitialized) {
                      return Text(
                        'Miliki sekarang',
                        style: thirdTextStyle.copyWith(
                          fontSize: SizeConfig.blockHorizontal! * 3.5,
                          letterSpacing: 0.085,
                          color: Color(0xff181818),
                        ),
                      );
                    } else if (state.stateProcess ==
                        paymentsProvider.Process.loading) {
                      return Container(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          color: eightColor,
                          strokeWidth: 2,
                        ),
                      );
                    }
                    return Text(
                      'Miliki sekarang',
                      style: thirdTextStyle.copyWith(
                        fontSize: SizeConfig.blockHorizontal! * 3.5,
                        letterSpacing: 0.085,
                        color: Color(0xff181818),
                      ),
                    );
                  }),
                ),
              ),
            ),
          ],
        ),
      );
    }

    Widget playCourseNav(String? courseId, String? instructor,
        String? thumbnail, String? title) {
      return Container(
          width: double.infinity,
          height: getProportionateScreenHeight(60),
          decoration: BoxDecoration(
              border:
                  Border.symmetric(horizontal: BorderSide(color: fourthColor)),
              boxShadow: [
                BoxShadow(
                    offset: Offset(0, -2),
                    blurRadius: 50,
                    color: fourthColor.withOpacity(0.15))
              ]),
          child: Center(
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                minimumSize: Size(getProportionateScreenWidth(90),
                    getProportionateScreenHeight(33)),
                backgroundColor: primaryColor,
              ),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => MultiProvider(
                      providers: [
                        ChangeNotifierProvider(
                          create: (context) =>
                              lessonCourseProvider.LessonCourseProvider(
                            lessonCourseService: LessonCourseService(),
                            id: int.parse(courseId ?? '0'),
                          ),
                        ),
                        ChangeNotifierProvider(
                            create: (context) => DetailCourseCouponProvider(
                                courseService: CourseService(),
                                id: courseId ?? '1',
                                coupon: coupon))
                      ],
                      child: PlayCourse(
                        judul: title ?? '',
                        instruktur: instructor ?? '',
                        thumbnail: thumbnail ??
                            '$baseUrl/uploads/courses_thumbnail/course_thumbnail_default_57.jpg',
                        courseeid: idcourse,
                      ),
                    ),
                  ),
                );
              },
              child: Text(
                'Lanjutkan Belajar',
                style: thirdTextStyle.copyWith(color: Colors.black),
              ),
            ),
          ));
    }

    Widget bottomNav(
        {required String discountPrice,
        required String idCourse,
        required String title,
        required String price,
        required String instructor,
        required String imageUrl}) {
      return Container(
        width: double.infinity,
        height: getProportionateScreenHeight(60),
        decoration: BoxDecoration(
            border:
                Border.symmetric(horizontal: BorderSide(color: fourthColor)),
            boxShadow: [
              BoxShadow(
                  offset: Offset(0, -2),
                  blurRadius: 50,
                  color: fourthColor.withOpacity(0.15))
            ]),
        child: Row(
          children: [
            SizedBox(
              width: 13,
            ),
            Text(
              numberFormat(discountPrice.toString().replaceAll('.', '')),
              style: primaryTextStyle.copyWith(
                  fontSize: getProportionateScreenHeight(20),
                  letterSpacing: 0.23),
            ),
            Spacer(),
            Container(
              width: getProportionateScreenWidth(39),
              height: getProportionateScreenHeight(34),
              decoration: BoxDecoration(
                border: Border.all(color: primaryColor),
                borderRadius: BorderRadius.circular(5),
              ),
              child: Consumer<wishlistProvider.WishlistProvider>(
                  builder: (context, state, _) {
                return IconButton(
                  padding: EdgeInsets.zero,
                  splashRadius: 17,
                  onPressed: () => state.data.contains(idcourse)
                      ? handleNotLogin()
                      : handleNotLoginWishlistNotExist(),
                  icon: Icon(FeatherIcons.shoppingCart,
                      color: primaryColor, size: 20),
                );
              }),
            ),
            // ),
            SizedBox(
              width: getProportionateScreenWidth(12),
            ),
            GestureDetector(
              onTap: () {
                int total = int.parse(discountPrice);
                selected.selectedTotalPrice =
                    total <= 50000 ? total + 5000 : total;
                print("Ini total price buat ke va ${selected.totalPrice}");
                handleNotLoginBuy(
                    title: title,
                    discountPrice: discountPrice,
                    imageUrl: imageUrl,
                    price: price,
                    instructor: instructor);
              },
              child: Container(
                margin: EdgeInsets.only(right: getProportionateScreenWidth(15)),
                width: getProportionateScreenWidth(113),
                height: getProportionateScreenHeight(33),
                decoration: BoxDecoration(
                    color: primaryColor,
                    borderRadius: BorderRadius.circular(5)),
                child: Center(
                    child: Text(
                  'Beli sekarang',
                  style: thirdTextStyle.copyWith(
                    fontSize: SizeConfig.blockHorizontal! * 3.5,
                    letterSpacing: 0.085,
                    color: Color(0xff181818),
                  ),
                )),
              ),
            )
          ],
        ),
      );
    }

    return SafeArea(
      child: MultiProvider(
        providers: [
          ChangeNotifierProvider(
            create: (context) => DetailCourseCouponProvider(
                courseService: CourseService(), id: idcourse, coupon: coupon),
          ),
          ChangeNotifierProvider(
            create: (context) =>
                detailRatingCourseProvider.DetailRatingCourseProvider(
                    courseService: CourseService(), id: idcourse),
          ),
          ChangeNotifierProvider(
            create: (context) =>
                sectionLessonCourseProvider.SectionLessonCourseProvider(
                    id: idcourse, sectionLessonService: SectionLessonService()),
          ),
        ],
        child: Consumer<DetailCourseCouponProvider>(
          builder: (context, state, _) {
            if (state.state == ResultState.Loading) {
              return Center(
                child: CircularProgressIndicator(
                  color: secondaryColor,
                  strokeWidth: 2,
                ),
              );
            } else if (state.state == ResultState.HasData) {
              var detailCourse = state.result!;

              return Scaffold(
                body: ListView(
                    physics: ScrollPhysics(),
                    shrinkWrap: true,
                    children: [
                      AppBarHeader(
                        idcourse: idcourse,
                      ),
                      HeaderCoupon(
                        dataDetailCourseModel: detailCourse,
                      ),
                      MultiProvider(
                        providers: [
                          ChangeNotifierProvider(
                            create: (context) =>
                                instructorProvider.InstructorProvider(
                                    instructorService: InstructorService(),
                                    id: int.parse(detailCourse.instructorId!)),
                          ),
                          ChangeNotifierProvider(
                              create: (context) => TabProvider()),
                        ],
                        child: CustomTabBar(
                          dataDetailCourseModel: detailCourse,
                          totalDuration: detailCourse.totalDuration,
                          bio: detailCourse.bio,
                          instructor: detailCourse.instructor,
                          rating: detailCourse.rating[0].avgRating.toString(),
                          review: detailCourse.rating[0].totalReview,
                          totalLesson: detailCourse.totalLesson,
                          totalStudent: detailCourse.totalStudents,
                        ),
                      ),
                    ]
                    // var finalRating = double.parse(

                    ),
                bottomNavigationBar: (detailCourse.isMine == 1)
                    ? playCourseNav(
                        detailCourse.id,
                        detailCourse.instructor,
                        detailCourse.thumbnail,
                        detailCourse.title,
                      )
                    : (detailCourse.isFreeCourse == '1' || typeCoupon == '1')
                        ? freeBottomNav(
                            detailCourse.id,
                            detailCourse.instructor,
                            detailCourse.thumbnail,
                            detailCourse.title,
                          )
                        : bottomNav(
                            discountPrice: detailCourse.discountPrice ?? ' ',
                            idCourse: detailCourse.id,
                            instructor: detailCourse.instructor ?? '',
                            price: detailCourse.price ?? '',
                            title: detailCourse.title ?? '',
                            imageUrl: detailCourse.thumbnail ??
                                '$baseUrl/uploads/courses_thumbnail/course_thumbnail_default_57.jpg'),
              );
            } else if (state.state == ResultState.NoData) {
              return Center(child: Text(state.message));
            } else if (state.state == ResultState.Error) {
              return Center(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text('Server internal Error'),
                  ],
                ),
              );
            } else {
              return Center(child: Text(''));
            }
          },
        ),
      ),
    );
  }
}
