import 'package:cherry_toast/cherry_toast.dart';
import 'package:cherry_toast/resources/arrays.dart';
import 'package:flutter/cupertino.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/helper/validator.dart';
import 'package:initial_folder/models/detail_course_model.dart';
import 'package:initial_folder/providers/detail_course_provider.dart';
import 'package:initial_folder/providers/tab_provider.dart';
import 'package:initial_folder/providers/total_price_provider.dart';
import 'package:initial_folder/screens/cart/cart_page.dart';
import 'package:initial_folder/screens/checkout/checkout_cart_coupon_page.dart';
import 'package:initial_folder/screens/checkout/detail_zero_payment.dart';
import 'package:initial_folder/screens/course/play_course_page.dart';
import 'package:initial_folder/screens/detail_course/components/app_bar.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/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:initial_folder/widgets/custom_navigator.dart';
import 'package:provider/provider.dart';
import 'package:tap_debouncer/tap_debouncer.dart';
import '../../services/user_info_service.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/order_provider.dart' as orderProvider;
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/payments_provider.dart'
    as paymentsProvider;
import 'package:initial_folder/providers/section_lesson_course_provider.dart'
    as sectionLessonCourseProvider;

class DetailVoucherScreen extends StatefulWidget {
  const DetailVoucherScreen({
    Key? key,
    required this.idcourse,
    this.coupon,
    this.resoaktifitas,
  }) : super(key: key);

  final String idcourse;
  final String? coupon;
  final String? resoaktifitas;
  static String routeName = "/course_detail";

  @override
  _DetailVoucherScreenState createState() => _DetailVoucherScreenState();
}

class _DetailVoucherScreenState extends State<DetailVoucherScreen> {
  late String cekstrAdmin = '';
  late DataDetailCourseModel dataDetailCourseModel;
  late int? iDuser;
  bool _isAdminChecked = false;
  ScrollController _scrollController = ScrollController();
  Color appBarColor = Colors.transparent;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels > 50) {
        setState(() {
          appBarColor = Theme.of(context).colorScheme.background;
        });
      } else {
        setState(() {
          appBarColor = Colors.transparent;
        });
      }
    });
    cekadminbaru();
    getIDuser();
  }

  void getIDuser() {
    UsersInfo().getIdUser().then((value) => {
          setState(() {
            iDuser = value;
          }),
        });
  }

  void cekadminbaru() {
    if (!_isAdminChecked) {
      UserInfoService().getDataDiriADMIN().then((value) => {
            if (value == 401)
              {
                setState(() {
                  cekstrAdmin = 'admin';
                }),
              }
            else
              {
                setState(() {
                  cekstrAdmin = 'user';
                }),
              },
            _isAdminChecked = true,
          });
    }
  }

  @override
  Widget build(BuildContext context) {
    final selectedTotalPrice = Provider.of<TotalPriceProvider>(context);
    final typeCoupon = Provider.of<TotalPriceProvider>(context).typeCoupon;
    List<String> idCarts = [];
    SizeConfig().init(context);
    paymentsProvider.PaymentsProvider pay =
        Provider.of<paymentsProvider.PaymentsProvider>(context);
    final finalPriceCoupon =
        Provider.of<TotalPriceProvider>(context).finalPriceCoupon;
    final potonganKupon = Provider.of<TotalPriceProvider>(context)
            .potonganKupon
            ?.round()
            .toString() ??
        '0';

    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 {
                  Future.delayed(Duration.zero, () {
                    Navigator.pop(context);
                    CherryToast.error(
                      animationDuration: Durations.long1,
                      title: Text("Terjadi Kesalahan, silahkan coba lagi",
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 15,
                          )),
                      animationType: AnimationType.fromTop,
                    ).show(context);
                  });
                  return Container();
                }
              },
            ),
          );
        },
      );
    }

    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 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).pushReplacement(
                          CustomNavigator(
                            child: CartPage(
                              idcourse: widget.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.close,
                      size: 40,
                      color: Colors.red,
                    ),
                    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).pushReplacement(
                          CustomNavigator(
                            child: CartPage(
                              idcourse: widget.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'),
                  ));
            }
          });
        },
      );
    }

    Future<void> _showMessageCart() {
      return showDialog<void>(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return Consumer<cartProvider.CartProvider>(
              builder: (context, state, _) {
            if (state.state == cartProvider.ResultState.loading) {
              return Center(
                child: CircularProgressIndicator(
                  strokeWidth: 1,
                  color: primaryColor,
                ),
              );
            } else if (state.state == cartProvider.ResultState.succes) {
              return Align(
                alignment: Alignment.center,
                child: Material(
                  type: MaterialType.transparency,
                  child: Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: getProportionateScreenWidth(20)),
                    child: Container(
                      decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.background,
                        borderRadius: BorderRadius.circular(5),
                        boxShadow: [
                          BoxShadow(
                            blurRadius: 10,
                            offset: Offset(0, 2),
                            color: Colors.black26,
                          )
                        ],
                      ),
                      child: Consumer<cartProvider.CartProvider>(
                        builder: (context, state, _) {
                          return Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              SizedBox(
                                  height: getProportionateScreenHeight(20)),
                              Padding(
                                padding: EdgeInsets.only(
                                    left: getProportionateScreenWidth(13)),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Text(
                                      'Kursus ini sudah berada dalam keranjang',
                                      textAlign: TextAlign.left,
                                      style: thirdTextStyle.copyWith(
                                        fontSize:
                                            getProportionateScreenWidth(12),
                                        fontWeight: reguler,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(
                                  height: getProportionateScreenHeight(20)),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  TextButton(
                                    style: ButtonStyle(
                                      overlayColor:
                                          MaterialStateProperty.all(sixColor),
                                      padding: MaterialStateProperty.all(
                                        EdgeInsets.symmetric(
                                            vertical: 1, horizontal: 1),
                                      ),
                                    ),
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                    },
                                    child: Text(
                                      'Batal',
                                      style: thirdTextStyle.copyWith(
                                        fontSize:
                                            getProportionateScreenWidth(12),
                                        color: primaryColor,
                                        fontWeight: reguler,
                                      ),
                                    ),
                                  ),
                                  TextButton(
                                    style: ButtonStyle(
                                      overlayColor:
                                          MaterialStateProperty.all(sixColor),
                                      padding: MaterialStateProperty.all(
                                        EdgeInsets.symmetric(
                                            vertical: 1, horizontal: 1),
                                      ),
                                    ),
                                    onPressed: () {
                                      Navigator.of(context).pushReplacement(
                                        CustomNavigator(
                                          child: CartPage(
                                            idcourse: widget.idcourse,
                                          ),
                                        ),
                                      );
                                    },
                                    child: Text(
                                      'Lihat keranjang',
                                      style: thirdTextStyle.copyWith(
                                        fontSize:
                                            getProportionateScreenWidth(12),
                                        color: primaryColor,
                                        fontWeight: reguler,
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                      width: getProportionateScreenWidth(10)),
                                ],
                              ),
                              SizedBox(height: getProportionateScreenHeight(5)),
                            ],
                          );
                        },
                      ),
                    ),
                  ),
                ),
              );
            } else if (state.state == cartProvider.ResultState.failed) {
              return SizedBox.shrink();
            } 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(widget.idcourse));
        await Provider.of<cartsProvider.CartsProvider>(context, listen: false)
            .getCarts();
      } 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(widget.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: widget.idcourse,
          title: title,
          price: finalPriceCoupon != 0
              ? finalPriceCoupon! < 50000
                  ? (finalPriceCoupon + 5000).toString()
                  : finalPriceCoupon.toString()
              : finalPriceCoupon.toString(),
          discountPrice: finalPriceCoupon.toString(),
          imageUrl: imageUrl,
          instructor: instructor,
        );
        int total;
        if (discountPrice == "0") {
          total = int.parse(price) < 50000
              ? int.parse(price) + 5000
              : int.parse(price);
        } else {
          total = int.parse(discountPrice) < 50000
              ? int.parse(discountPrice) + 5000
              : int.parse(discountPrice);
        }
        Provider.of<orderProvider.OrderProvider>(context, listen: false)
            .getTotalPrice(total.toString());
        Navigator.of(context, rootNavigator: true).push(
          CustomNavigator(
            child: CheckoutCartCouponPage(
              idCart: idCarts,
              potonganKupon: int.parse(potonganKupon.toString()),
              discountHarga: discountPrice == "0"
                  ? int.parse(price)
                  : int.parse(discountPrice),
            ),
          ),
        );
      } 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.freeCourseCoupon(
            int.parse(widget.idcourse), widget.coupon!)) {
          await Provider.of<myCourseProvider.MyCourseProvider>(context,
                  listen: false)
              .getMyCourse();
          Navigator.pushReplacement(
            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? instructorId,
        String? thumbnail,
        String? title,
        String? statuscourse,
        String isadmin) {
      return Container(
        width: double.infinity,
        height: getProportionateScreenHeight(60),
        decoration: BoxDecoration(
          color: Theme.of(context).brightness == Brightness.dark
              ? twelveColor
              : baruTextutih,
          boxShadow: [
            BoxShadow(
              color: baruTexthitam.withOpacity(0.1),
              offset: Offset(0, 1),
              blurRadius: 9,
              spreadRadius: 6,
            ),
          ],
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if ('$instructorId' == '$iDuser')
              TapDebouncer(
                cooldown: const Duration(milliseconds: 3500),
                onTap: () async => await {
                  print('user nya sama'),
                  CherryToast.error(
                    animationDuration: Durations.long1,
                    title: Text(
                      "Tidak bisa membeli kursus milik anda sendiri",
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 15,
                      ),
                    ),
                    animationType: AnimationType.fromTop,
                  ).show(context)
                },
                builder: (BuildContext context, TapDebouncerFunc? onTap) {
                  return GestureDetector(
                    onTap: onTap,
                    child: Container(
                      margin: EdgeInsets.only(
                          right: getProportionateScreenWidth(15)),
                      width: getProportionateScreenWidth(123),
                      height: getProportionateScreenHeight(33),
                      decoration: BoxDecoration(
                          color: fiveColor,
                          borderRadius: BorderRadius.circular(5)),
                      child: Center(
                        child: Consumer<paymentsProvider.PaymentsProvider>(
                            builder: (context, state, _) {
                          if (state.stateProcess ==
                              paymentsProvider.Process.uninitialized) {
                            Container(
                              width: getProportionateScreenWidth(140),
                              height: getProportionateScreenHeight(40),
                              decoration: BoxDecoration(
                                  color: primaryColor,
                                  borderRadius: BorderRadius.circular(10)),
                              child: Center(
                                child: Text(
                                  'Miliki Sekarang',
                                  style: thirdTextStyle.copyWith(
                                    fontSize: getProportionateScreenWidth(15),
                                    letterSpacing: 0.085,
                                    color: baruTextutih,
                                  ),
                                ),
                              ),
                            );
                          } else if (state.stateProcess ==
                              paymentsProvider.Process.loading) {
                            return Container(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(
                                color: eightColor,
                                strokeWidth: 2,
                              ),
                            );
                          }
                          return Container(
                            width: getProportionateScreenWidth(140),
                            height: getProportionateScreenHeight(40),
                            decoration: BoxDecoration(
                                color: primaryColor,
                                borderRadius: BorderRadius.circular(10)),
                            child: Center(
                              child: Text(
                                'Miliki Sekarang',
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(15),
                                  letterSpacing: 0.085,
                                  color: baruTextutih,
                                ),
                              ),
                            ),
                          );
                        }),
                      ),
                    ),
                  );
                },
              )
            else if (isadmin == 'admin')
              GestureDetector(
                onTap: () {
                  print('disabled');
                },
                child: Container(
                  margin:
                      EdgeInsets.only(right: getProportionateScreenWidth(15)),
                  width: getProportionateScreenWidth(123),
                  height: getProportionateScreenHeight(33),
                  decoration: BoxDecoration(
                      color: fiveColor, borderRadius: BorderRadius.circular(5)),
                  child: Center(
                    child: Consumer<paymentsProvider.PaymentsProvider>(
                        builder: (context, state, _) {
                      if (state.stateProcess ==
                          paymentsProvider.Process.uninitialized) {
                        return Container(
                          width: getProportionateScreenWidth(140),
                          height: getProportionateScreenHeight(40),
                          decoration: BoxDecoration(
                              color: primaryColor,
                              borderRadius: BorderRadius.circular(10)),
                          child: Center(
                            child: Text(
                              'Miliki Sekarang',
                              style: thirdTextStyle.copyWith(
                                fontSize: getProportionateScreenWidth(15),
                                letterSpacing: 0.085,
                                color: baruTextutih,
                              ),
                            ),
                          ),
                        );
                      } else if (state.stateProcess ==
                          paymentsProvider.Process.loading) {
                        return Container(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            color: eightColor,
                            strokeWidth: 2,
                          ),
                        );
                      }
                      return Container(
                        width: getProportionateScreenWidth(140),
                        height: getProportionateScreenHeight(40),
                        decoration: BoxDecoration(
                            color: primaryColor,
                            borderRadius: BorderRadius.circular(10)),
                        child: Center(
                          child: Text(
                            'Miliki Sekarang',
                            style: thirdTextStyle.copyWith(
                              fontSize: getProportionateScreenWidth(15),
                              letterSpacing: 0.085,
                              color: baruTextutih,
                            ),
                          ),
                        ),
                      );
                    }),
                  ),
                ),
              )
            else if (statuscourse == 'private')
              TapDebouncer(
                cooldown: const Duration(milliseconds: 3500),
                onTap: () async => await {
                  print('disabled private'),
                  CherryToast.error(
                    animationDuration: Durations.long1,
                    title: Text(
                      "Kursus sedang dalam status\ntidak aktif",
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 15,
                      ),
                    ),
                    animationType: AnimationType.fromTop,
                  ).show(context)
                },
                builder: (BuildContext context, TapDebouncerFunc? onTap) {
                  return GestureDetector(
                    onTap: onTap,
                    child: Container(
                      margin: EdgeInsets.only(
                          right: getProportionateScreenWidth(15)),
                      width: getProportionateScreenWidth(123),
                      height: getProportionateScreenHeight(33),
                      decoration: BoxDecoration(
                          color: fiveColor,
                          borderRadius: BorderRadius.circular(5)),
                      child: Center(
                        child: Consumer<paymentsProvider.PaymentsProvider>(
                            builder: (context, state, _) {
                          if (state.stateProcess ==
                              paymentsProvider.Process.uninitialized) {
                            return Container(
                              width: getProportionateScreenWidth(140),
                              height: getProportionateScreenHeight(40),
                              decoration: BoxDecoration(
                                  color: primaryColor,
                                  borderRadius: BorderRadius.circular(10)),
                              child: Center(
                                child: Text(
                                  'Miliki Sekarang',
                                  style: thirdTextStyle.copyWith(
                                    fontSize: getProportionateScreenWidth(15),
                                    letterSpacing: 0.085,
                                    color: baruTextutih,
                                  ),
                                ),
                              ),
                            );
                          } else if (state.stateProcess ==
                              paymentsProvider.Process.loading) {
                            return Container(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(
                                color: eightColor,
                                strokeWidth: 2,
                              ),
                            );
                          }
                          return Container(
                            width: getProportionateScreenWidth(140),
                            height: getProportionateScreenHeight(40),
                            decoration: BoxDecoration(
                                color: primaryColor,
                                borderRadius: BorderRadius.circular(10)),
                            child: Center(
                              child: Text(
                                'Miliki Sekarang',
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(15),
                                  letterSpacing: 0.085,
                                  color: baruTextutih,
                                ),
                              ),
                            ),
                          );
                        }),
                      ),
                    ),
                  );
                },
              )
            else if (statuscourse != 'active')
              TapDebouncer(
                cooldown: const Duration(milliseconds: 3500),
                onTap: () async => await {
                  print('disabled ini'),
                  CherryToast.error(
                    animationDuration: Durations.long1,
                    title: Text(
                      "Kursus sedang dalam status\ntidak aktif",
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 15,
                      ),
                    ),
                    animationType: AnimationType.fromTop,
                  ).show(context)
                },
                builder: (BuildContext context, TapDebouncerFunc? onTap) {
                  return GestureDetector(
                    onTap: onTap,
                    child: Container(
                      margin: EdgeInsets.only(
                          right: getProportionateScreenWidth(15)),
                      width: getProportionateScreenWidth(123),
                      height: getProportionateScreenHeight(33),
                      decoration: BoxDecoration(
                          color: fiveColor,
                          borderRadius: BorderRadius.circular(5)),
                      child: Center(
                        child: Consumer<paymentsProvider.PaymentsProvider>(
                            builder: (context, state, _) {
                          if (state.stateProcess ==
                              paymentsProvider.Process.uninitialized) {
                            return Container(
                              width: getProportionateScreenWidth(113),
                              height: getProportionateScreenHeight(33),
                              decoration: BoxDecoration(
                                  color: primaryColor,
                                  borderRadius: BorderRadius.circular(8)),
                              child: Center(
                                child: Text(
                                  'Segera Hadir',
                                  style: thirdTextStyle.copyWith(
                                    fontSize: SizeConfig.blockHorizontal! * 3.5,
                                    letterSpacing: 0.085,
                                    color: baruTextutih,
                                  ),
                                ),
                              ),
                            );
                          } else if (state.stateProcess ==
                              paymentsProvider.Process.loading) {
                            return Container(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(
                                color: eightColor,
                                strokeWidth: 2,
                              ),
                            );
                          }
                          return Container(
                            width: getProportionateScreenWidth(140),
                            height: getProportionateScreenHeight(40),
                            decoration: BoxDecoration(
                                color: primaryColor,
                                borderRadius: BorderRadius.circular(10)),
                            child: Center(
                              child: Text(
                                'Miliki Sekarang',
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(15),
                                  letterSpacing: 0.085,
                                  color: baruTextutih,
                                ),
                              ),
                            ),
                          );
                        }),
                      ),
                    ),
                  );
                },
              )
            else
              GestureDetector(
                onTap: () =>
                    handleNotLoginFree(courseId, title, thumbnail, instructor),
                child: Center(
                  child: Consumer<paymentsProvider.PaymentsProvider>(
                    builder: (context, state, _) {
                      if (state.stateProcess ==
                          paymentsProvider.Process.uninitialized) {
                        return Container(
                          width: getProportionateScreenWidth(140),
                          height: getProportionateScreenHeight(40),
                          decoration: BoxDecoration(
                              color: primaryColor,
                              borderRadius: BorderRadius.circular(10)),
                          child: Center(
                            child: Text(
                              'Miliki Sekarang',
                              style: thirdTextStyle.copyWith(
                                fontSize: getProportionateScreenWidth(15),
                                letterSpacing: 0.085,
                                color: baruTextutih,
                              ),
                            ),
                          ),
                        );
                      } else if (state.stateProcess ==
                          paymentsProvider.Process.loading) {
                        return Container(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            color: eightColor,
                            strokeWidth: 2,
                          ),
                        );
                      }
                      return Container(
                        width: getProportionateScreenWidth(140),
                        height: getProportionateScreenHeight(40),
                        decoration: BoxDecoration(
                            color: primaryColor,
                            borderRadius: BorderRadius.circular(10)),
                        child: Center(
                          child: Text(
                            'Miliki Sekarang',
                            style: thirdTextStyle.copyWith(
                              fontSize: getProportionateScreenWidth(15),
                              letterSpacing: 0.085,
                              color: baruTextutih,
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ),
          ],
        ),
      );
    }

    Widget playCourseNav(String? courseId, String? instructor,
        String? thumbnail, String? title) {
      return Container(
        width: double.infinity,
        height: getProportionateScreenHeight(60),
        decoration: BoxDecoration(
          color: Theme.of(context).brightness == Brightness.dark
              ? twelveColor
              : baruTextutih,
          boxShadow: [
            BoxShadow(
              color: baruTexthitam.withOpacity(0.1),
              offset: Offset(0, 1),
              blurRadius: 9,
              spreadRadius: 6,
            ),
          ],
        ),
        child: GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => MultiProvider(
                  providers: [
                    ChangeNotifierProvider(
                      create: (context) =>
                          lessonCourseProvider.LessonCourseProvider(
                        lessonCourseService: LessonCourseService(),
                        id: int.parse(courseId ?? '0'),
                      ),
                    ),
                    ChangeNotifierProvider(
                      create: (context) => DetailCourseProvider(
                          courseService: CourseService(), id: courseId ?? '1'),
                    )
                  ],
                  child: PlayCourse(
                    judul: title ?? '',
                    instruktur: instructor ?? '',
                    thumbnail: thumbnail ??
                        '$baseUrl/uploads/courses_thumbnail/course_thumbnail_default_57.jpg',
                    courseeid: courseId ?? '',
                  ),
                ),
              ),
            );
          },
          child: Container(
            margin: EdgeInsets.symmetric(
              horizontal: getProportionateScreenWidth(110),
              vertical: getProportionateScreenHeight(10),
            ),
            decoration: BoxDecoration(
                color: primaryColor, borderRadius: BorderRadius.circular(10)),
            child: Center(
              child: Text(
                'Lanjutkan Belajar',
                style: thirdTextStyle.copyWith(
                  fontSize: SizeConfig.blockHorizontal! * 3.5,
                  letterSpacing: 0.085,
                  color: baruTextutih,
                ),
              ),
            ),
          ),
        ),
      );
    }

    Widget bottomNav(
        {required String discountPrice,
        required String idCourse,
        required String title,
        required String price,
        required String instructor,
        required String? instructorId,
        required String imageUrl,
        required String statuscourse,
        required String isadmin}) {
      return Container(
        width: double.infinity,
        height: getProportionateScreenHeight(60),
        decoration: BoxDecoration(
          color: Theme.of(context).brightness == Brightness.dark
              ? twelveColor
              : baruTextutih,
          boxShadow: [
            BoxShadow(
              color: baruTexthitam.withOpacity(0.1),
              offset: Offset(0, 1),
              blurRadius: 9,
              spreadRadius: 6,
            ),
          ],
        ),
        child: Padding(
          padding:
              EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(15)),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              if ('$instructorId' == '$iDuser')
                TapDebouncer(
                  cooldown: const Duration(milliseconds: 3500),
                  onTap: () async => await {
                    CherryToast.error(
                      animationDuration: Durations.long1,
                      title: Text(
                        "Anda Tidak bisa membeli kursus milik anda sendiri",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 15,
                        ),
                      ),
                      animationType: AnimationType.fromTop,
                    ).show(context)
                  },
                  builder: (BuildContext context, TapDebouncerFunc? onTap) {
                    return GestureDetector(
                      onTap: onTap,
                      child: Container(
                        width: getProportionateScreenWidth(140),
                        height: getProportionateScreenHeight(40),
                        decoration: BoxDecoration(
                            color: primaryColor,
                            borderRadius: BorderRadius.circular(10)),
                        child: Center(
                          child: Text(
                            'Beli Sekarang',
                            style: thirdTextStyle.copyWith(
                              fontSize: getProportionateScreenWidth(15),
                              letterSpacing: 0.085,
                              color: baruTextutih,
                            ),
                          ),
                        ),
                      ),
                    );
                  },
                )
              else if (isadmin == 'admin' && statuscourse == 'prepublish')
                GestureDetector(
                  onTap: () {
                    print('jadi admin');
                  },
                  child: Container(
                    margin:
                        EdgeInsets.only(right: getProportionateScreenWidth(15)),
                    width: getProportionateScreenWidth(113),
                    height: getProportionateScreenHeight(33),
                    decoration: BoxDecoration(
                        color: primaryColor,
                        borderRadius: BorderRadius.circular(8)),
                    child: Center(
                      child: Text(
                        'Segera Hadir',
                        style: thirdTextStyle.copyWith(
                          fontSize: SizeConfig.blockHorizontal! * 3.5,
                          letterSpacing: 0.085,
                          color: baruTextutih,
                        ),
                      ),
                    ),
                  ),
                )
              else if (cekstrAdmin == 'admin')
                GestureDetector(
                  onTap: () {
                    print('jadi admin');
                  },
                  child: Container(
                    width: getProportionateScreenWidth(140),
                    height: getProportionateScreenHeight(40),
                    decoration: BoxDecoration(
                        color: primaryColor,
                        borderRadius: BorderRadius.circular(10)),
                    child: Center(
                      child: Text(
                        'Beli Sekarang',
                        style: thirdTextStyle.copyWith(
                          fontSize: getProportionateScreenWidth(15),
                          letterSpacing: 0.085,
                          color: baruTextutih,
                        ),
                      ),
                    ),
                  ),
                )
              else if (statuscourse == 'prepublish')
                TapDebouncer(
                  cooldown: const Duration(milliseconds: 3500),
                  onTap: () async => await {
                    CherryToast.error(
                      animationDuration: Durations.long1,
                      title: Text(
                        "Kursus sedang dalam status\ntidak aktif",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 15,
                        ),
                      ),
                      animationType: AnimationType.fromTop,
                    ).show(context)
                  },
                  builder: (BuildContext context, TapDebouncerFunc? onTap) {
                    return GestureDetector(
                      onTap: onTap,
                      child: Container(
                        margin: EdgeInsets.only(
                            right: getProportionateScreenWidth(15)),
                        width: getProportionateScreenWidth(113),
                        height: getProportionateScreenHeight(33),
                        decoration: BoxDecoration(
                            color: primaryColor,
                            borderRadius: BorderRadius.circular(8)),
                        child: Center(
                          child: Text(
                            'Segera Hadir',
                            style: thirdTextStyle.copyWith(
                              fontSize: SizeConfig.blockHorizontal! * 3.5,
                              letterSpacing: 0.085,
                              color: baruTextutih,
                            ),
                          ),
                        ),
                      ),
                    );
                  },
                )
              else if (statuscourse == 'private')
                TapDebouncer(
                  cooldown: const Duration(milliseconds: 3500),
                  onTap: () async => await {
                    CherryToast.error(
                      animationDuration: Durations.long1,
                      title: Text(
                        "Kursus sedang dalam status\ntidak aktif",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 15,
                        ),
                      ),
                      animationType: AnimationType.fromTop,
                    ).show(context)
                  },
                  builder: (BuildContext context, TapDebouncerFunc? onTap) {
                    return GestureDetector(
                      onTap: onTap,
                      child: Container(
                        width: getProportionateScreenWidth(140),
                        height: getProportionateScreenHeight(40),
                        decoration: BoxDecoration(
                            color: primaryColor,
                            borderRadius: BorderRadius.circular(10)),
                        child: Center(
                          child: Text(
                            'Beli Sekarang',
                            style: thirdTextStyle.copyWith(
                              fontSize: getProportionateScreenWidth(15),
                              letterSpacing: 0.085,
                              color: baruTextutih,
                            ),
                          ),
                        ),
                      ),
                    );
                  },
                )
              else if (statuscourse != 'active')
                TapDebouncer(
                  cooldown: const Duration(milliseconds: 3500),
                  onTap: () async => await {
                    CherryToast.error(
                      animationDuration: Durations.long1,
                      title: Text(
                        "Kursus sedang dalam status\ntidak aktif",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 15,
                        ),
                      ),
                      animationType: AnimationType.fromTop,
                    ).show(context)
                  },
                  builder: (BuildContext context, TapDebouncerFunc? onTap) {
                    return GestureDetector(
                      onTap: onTap,
                      child: Container(
                        margin: EdgeInsets.only(
                            right: getProportionateScreenWidth(15)),
                        width: getProportionateScreenWidth(113),
                        height: getProportionateScreenHeight(33),
                        decoration: BoxDecoration(
                            color: primaryColor,
                            borderRadius: BorderRadius.circular(8)),
                        child: Center(
                          child: Text(
                            'Segera Hadir',
                            style: thirdTextStyle.copyWith(
                              fontSize: SizeConfig.blockHorizontal! * 3.5,
                              letterSpacing: 0.085,
                              color: baruTextutih,
                            ),
                          ),
                        ),
                      ),
                    );
                  },
                )
              else
                GestureDetector(
                  onTap: () {
                    print(
                        '4  ${selectedTotalPrice.selectedTotalPrice = int.parse(discountPrice)}');
                    selectedTotalPrice.selectedTotalPrice = discountPrice == "0"
                        ? (int.parse(price) < 50000
                            ? int.parse(price) + 5000
                            : int.parse(price))
                        : (int.parse(discountPrice) < 50000
                            ? int.parse(discountPrice) + 5000
                            : int.parse(discountPrice));
                    if (numberFormat(discountPrice) == 'Rp. 0') {
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (context) => DetailZeroPayment(),
                        ),
                      );
                      handleNotLoginBuy(
                        title: title,
                        discountPrice: discountPrice,
                        imageUrl: imageUrl,
                        price: price,
                        instructor: instructor,
                      );
                    }
                    handleNotLoginBuy(
                      title: title,
                      discountPrice: discountPrice,
                      imageUrl: imageUrl,
                      price: price,
                      instructor: instructor,
                    );
                  },
                  child: Container(
                    width: getProportionateScreenWidth(140),
                    height: getProportionateScreenHeight(40),
                    decoration: BoxDecoration(
                        color: primaryColor,
                        borderRadius: BorderRadius.circular(10)),
                    child: Center(
                      child: Text(
                        'Beli Sekarang',
                        style: thirdTextStyle.copyWith(
                          fontSize: getProportionateScreenWidth(15),
                          letterSpacing: 0.085,
                          color: baruTextutih,
                        ),
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),
      );
    }

    return (cekstrAdmin == "")
        ? Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          )
        : SafeArea(
            child: MultiProvider(
              providers: [
                ChangeNotifierProvider(
                  create: (context) => DetailCourseProvider(
                    courseService: CourseService(),
                    id: widget.idcourse,
                  ),
                ),
                ChangeNotifierProvider(
                  create: (context) =>
                      detailRatingCourseProvider.DetailRatingCourseProvider(
                          courseService: CourseService(), id: widget.idcourse),
                ),
                ChangeNotifierProvider(
                  create: (context) =>
                      sectionLessonCourseProvider.SectionLessonCourseProvider(
                          id: widget.idcourse,
                          sectionLessonService: SectionLessonService()),
                ),
              ],
              child: Consumer<DetailCourseProvider>(
                builder: (context, state, _) {
                  cekadminbaru();
                  if (state.state == ResultState.Loading) {
                    return Center(
                      child: CircularProgressIndicator(
                        color: secondaryColor,
                        strokeWidth: 2,
                      ),
                    );
                  } else if (state.state == ResultState.HasData) {
                    var detailCourse = state.result!.data[0][0];
                    return Scaffold(
                      body: Stack(
                        children: [
                          ListView(
                            controller: _scrollController,
                            physics: ScrollPhysics(),
                            shrinkWrap: true,
                            children: [
                              Header(
                                dataDetailCourseModel: detailCourse,
                                coupon: widget.coupon,
                              ),
                              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,
                                  fotoProfile: detailCourse.fotoProfile,
                                  rating: detailCourse.rating[0].avgRating
                                      .toString(),
                                  review: detailCourse.rating[0].totalReview,
                                  totalLesson: detailCourse.totalLesson,
                                  totalStudent: detailCourse.totalStudents,
                                  headline: detailCourse.headlineInstructor,
                                  resoaktifitas: widget.resoaktifitas,
                                  idCategory:
                                      detailCourse.breadcrumbs.idCategory,
                                ),
                              ),
                            ],
                          ),
                          AppBarHeader(
                            idcourse: widget.idcourse,
                            color: appBarColor,
                          ),
                        ],
                      ),
                      bottomNavigationBar: (detailCourse.isMine == 1)
                          ? playCourseNav(
                              detailCourse.id,
                              detailCourse.instructor,
                              detailCourse.thumbnail,
                              detailCourse.title,
                            )
                          : (detailCourse.isFreeCourse == '1' ||
                                  typeCoupon == "1")
                              ? freeBottomNav(
                                  detailCourse.id,
                                  detailCourse.instructor,
                                  detailCourse.instructorId,
                                  detailCourse.thumbnail,
                                  detailCourse.title,
                                  detailCourse.status_course,
                                  cekstrAdmin)
                              : bottomNav(
                                  discountPrice:
                                      detailCourse.discountPrice ?? ' ',
                                  idCourse: detailCourse.id,
                                  instructor: detailCourse.instructor!,
                                  instructorId: detailCourse.instructorId!,
                                  price: detailCourse.price!,
                                  title: detailCourse.title!,
                                  imageUrl: detailCourse.thumbnail ?? '',
                                  statuscourse:
                                      detailCourse.status_course ?? '',
                                  isadmin: cekstrAdmin),
                    );
                  } else if (state.state == ResultState.NoData) {
                    return Center(child: Text(state.message));
                  } else if (state.state == ResultState.Error) {
                    return const Scaffold(
                      body: Center(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text('Error 500: Terdapat kesalahan pada server'),
                          ],
                        ),
                      ),
                    );
                  } else {
                    return const Scaffold(
                      body: Center(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text('Terjadi kesalahan, sebaiknya hati-hati'),
                          ],
                        ),
                      ),
                    );
                  }
                },
              ),
            ),
          );
  }
}
