import 'package:cached_network_image/cached_network_image.dart';
import 'package:cherry_toast/cherry_toast.dart';
import 'package:cherry_toast/resources/arrays.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_svg/flutter_svg.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/models/voucher_model.dart';
import 'package:initial_folder/providers/carts_provider.dart';
import 'package:initial_folder/providers/my_course_provider.dart';
import 'package:initial_folder/providers/order_provider.dart';
import 'package:initial_folder/providers/radeem_voucher_provider.dart';
import 'package:initial_folder/providers/theme_provider.dart';
import 'package:initial_folder/providers/total_price_provider.dart';
import 'package:initial_folder/providers/wishlist_post_provider.dart';
import 'package:initial_folder/screens/checkout/checkout_detail_coupon.dart';
import 'package:initial_folder/screens/checkout/components/field_kupon.dart';
import 'package:initial_folder/screens/detail_course/components/murid_and_rating.dart';
import 'package:initial_folder/screens/login/login_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/services/user_info_service.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/login_regist/default_button.dart';
import 'package:initial_folder/widgets/login_regist/loading_button.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';
import 'package:tap_debouncer/tap_debouncer.dart';
import 'package:initial_folder/providers/payments_provider.dart' as paysProv;
import 'package:initial_folder/providers/detail_course_provider.dart'
    as detailCourseProv;
import 'package:initial_folder/providers/whislist_provider.dart'
    as wishlistProvider;

class Header extends StatefulWidget {
  const Header(
      {Key? key,
      required this.dataDetailCourseModel,
      this.coupon,
      this.discountPrice,
      this.price,
      this.idCourse})
      : super(key: key);

  final DataDetailCourseModel dataDetailCourseModel;
  final String? coupon;
  final String? discountPrice;
  final String? price;
  final String? idCourse;

  @override
  State<Header> createState() => _HeaderState();
}

class _HeaderState extends State<Header> {
  @override
  bool isAdmin = false;
  int? iDuser;
  String? tokenCek;

  void cekadmin() {
    UserInfoService().getDataDiriADMIN().then((value) => {
          if (value == 401)
            {
              setState(() {
                isAdmin = true;
              })
            }
        });
  }

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

  void getTokenuser() {
    UsersInfo().getToken().then((value) => {
          setState(() {
            tokenCek = value;
          }),
        });
  }

  @override
  void initState() {
    super.initState();
    cekadmin();
    getIDuser();
    getTokenuser();
  }

  Widget build(BuildContext context) {
    final selected = Provider.of<TotalPriceProvider>(context);
    final kuponController = TextEditingController();
    final themeProvider = Provider.of<ThemeProvider>(context);
    final finalPriceCoupon =
        Provider.of<TotalPriceProvider>(context).finalPriceCoupon;
    String? kuponErrorMessage = "";
    bool isLoading = false;
    WishlistPostProvider wishlistPostProvider =
        Provider.of<WishlistPostProvider>(context);
    paysProv.PaymentsProvider pay =
        Provider.of<paysProv.PaymentsProvider>(context);

    showNotifDialog(BuildContext context) {
      showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            content: Consumer<paysProv.PaymentsProvider>(
              builder: (context, state, child) {
                if (state.state == paysProv.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() {
      return showDialog(
        context: context,
        builder: (context) => AlertDialog(
          contentPadding: EdgeInsets.fromLTRB(12, 20, 12, 1),
          content: Text(
            'Mohon login terlebih dahulu sebelum menambahkan ke wishlist',
            style: primaryTextStyle.copyWith(
                fontSize: getProportionateScreenWidth(12), letterSpacing: 1),
          ),
          actions: [
            GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Text(
                'Batal',
                style: primaryTextStyle.copyWith(
                  fontSize: getProportionateScreenWidth(12),
                  letterSpacing: 1,
                  color: primaryColor,
                ),
              ),
            ),
            SizedBox(width: getProportionateScreenWidth(5)),
            GestureDetector(
              onTap: () => Navigator.of(context).pushNamedAndRemoveUntil(
                  LoginEmail.routeName, (Route<dynamic> route) => false),
              child: Text(
                'Login',
                style: primaryTextStyle.copyWith(
                    fontSize: getProportionateScreenWidth(12),
                    letterSpacing: 1,
                    color: primaryColor),
              ),
            ),
          ],
        ),
      );
    }

    Future _showDialogNotLoginKupon() {
      return showDialog(
        context: context,
        builder: (context) => AlertDialog(
          contentPadding: EdgeInsets.fromLTRB(12, 20, 12, 1),
          content: Text(
            'Mohon login terlebih dahulu sebelum tukar kupon',
            style: primaryTextStyle.copyWith(
                fontSize: getProportionateScreenWidth(12), letterSpacing: 1),
          ),
          actions: [
            GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Text(
                'Batal',
                style: primaryTextStyle.copyWith(
                  fontSize: getProportionateScreenWidth(12),
                  letterSpacing: 1,
                  color: primaryColor,
                ),
              ),
            ),
            SizedBox(width: getProportionateScreenWidth(5)),
            GestureDetector(
              onTap: () => Navigator.of(context).pushNamedAndRemoveUntil(
                  LoginEmail.routeName, (Route<dynamic> route) => false),
              child: Text(
                'Login',
                style: primaryTextStyle.copyWith(
                  fontSize: getProportionateScreenWidth(12),
                  letterSpacing: 1,
                  color: primaryColor,
                ),
              ),
            ),
          ],
        ),
      );
    }

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

    addWishlistNotExist() async {
      var connectivityResult = await (Connectivity().checkConnectivity());
      if (connectivityResult == ConnectivityResult.none) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            duration: Duration(seconds: 1),
            backgroundColor: Colors.red[600],
            content: Text(
              'No Internet Connections',
              textAlign: TextAlign.center,
              style: primaryTextStyle.copyWith(color: Colors.white),
            ),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(5),
            ),
          ),
        );
      } else {
        await wishlistPostProvider
            .addWishlist(int.parse(widget.dataDetailCourseModel.id));
        await Provider.of<wishlistProvider.WishlistProvider>(context,
                listen: false)
            .getWishlist()
            .then(
              (value) => {
                if (value == "gagal")
                  {
                    CherryToast.error(
                      animationDuration: Durations.long1,
                      title: Text(
                        "Terjadi kesalahan, silahkan coba lagi",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 15,
                        ),
                      ),
                      animationType: AnimationType.fromTop,
                    ).show(context)
                  }
              },
            );
      }
    }

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

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

    Future _showKupon() {
      setState(() {
        kuponErrorMessage = "";
      });
      return showModalBottomSheet(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(0),
        ),
        elevation: 0.0,
        context: context,
        isScrollControlled: true,
        builder: (context) {
          return Padding(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            child: SingleChildScrollView(
              child: Container(
                color: Theme.of(context).colorScheme.background,
                padding: EdgeInsets.all(16.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        IconButton(
                          icon: Icon(Icons.close),
                          onPressed: () {
                            Navigator.pop(context);
                          },
                        ),
                      ],
                    ),
                    Center(
                      child: Column(
                        children: [
                          Text(
                            'Tukarkan Voucher',
                            style: thirdTextStyle.copyWith(
                                letterSpacing: 1,
                                fontWeight: semiBold,
                                fontSize: getProportionateScreenWidth(14)),
                          ),
                          SizedBox(height: getProportionateScreenHeight(16)),
                          Text(
                            'Masukkan kode kupon untuk klaim\npromo menarik Vocasia',
                            textAlign: TextAlign.center,
                            style: primaryTextStyle.copyWith(
                                fontWeight: reguler,
                                fontSize: getProportionateScreenWidth(12)),
                          ),
                          SizedBox(height: getProportionateScreenHeight(30)),
                          Padding(
                            padding: EdgeInsets.symmetric(
                                horizontal: getProportionateScreenWidth(16)),
                            child: FieldKupon(
                              controler: kuponController,
                            ),
                          ),
                          SizedBox(height: getProportionateScreenHeight(7)),
                          Padding(
                            padding: EdgeInsets.symmetric(
                                horizontal: getProportionateScreenWidth(15)),
                            child: isLoading
                                ? LoadingButton(
                                    backgroundButtonColor: primaryColor,
                                    textButtonColor: Color(0xff050505),
                                  )
                                : TapDebouncer(
                                    cooldown:
                                        const Duration(milliseconds: 3000),
                                    onTap: () async {
                                      final voucher = kuponController.text;
                                      var radeemVoucherProvider =
                                          Provider.of<RadeemVoucherProvider>(
                                              context,
                                              listen: false);
                                      VoucherModel? response =
                                          await radeemVoucherProvider
                                              .radeemVoucher(
                                                  int.parse(widget
                                                      .dataDetailCourseModel
                                                      .id),
                                                  voucher);
                                      if (response?.error == false) {
                                        await Provider.of<CartsProvider>(
                                                context,
                                                listen: false)
                                            .getCarts();
                                        VoucherModel? detailKupon =
                                            radeemVoucherProvider.result;
                                        DataVoucher? firstDataItem =
                                            detailKupon?.data?.first;
                                        Provider.of<OrderProvider>(context,
                                                listen: false)
                                            .clear();
                                        var finalPriceReal = firstDataItem
                                            ?.finalPrice
                                            .toString()
                                            .replaceAll(".", "");
                                        int? discountPriceRounded =
                                            firstDataItem?.discountPrice
                                                    ?.round() ??
                                                0;
                                        if (firstDataItem?.typeCoupon != "1" ||
                                            firstDataItem?.finalPrice == 0 ||
                                            firstDataItem
                                                    ?.finalPrice.toString ==
                                                "0")
                                          Provider.of<OrderProvider>(context,
                                                  listen: false)
                                              .addOrder(
                                            id: firstDataItem?.idCourse,
                                            title: firstDataItem?.courseName,
                                            price: finalPriceReal,
                                            discountPrice: finalPriceReal,
                                            imageUrl: firstDataItem
                                                        ?.thubmnail ==
                                                    null
                                                ? '$baseUrl/uploads/courses_thumbnail/course_thumbnail_default_57.jpg'
                                                : firstDataItem?.thubmnail,
                                            instructor:
                                                firstDataItem?.instructor,
                                          );
                                        selected.selectedPriceCoupon =
                                            int.parse(
                                                firstDataItem?.originalPrice ??
                                                    "0");
                                        selected.selectedTypeCoupon =
                                            firstDataItem?.typeCoupon ?? "";
                                        selected.selectedCouponText =
                                            voucher.toString();
                                        selected.selectedFinalPriceCoupon =
                                            int.parse(firstDataItem!.finalPrice
                                                .toString());
                                        selected.selectedTotalPrice = int.parse(
                                            firstDataItem.finalPrice
                                                .toString());
                                        selected.selectedTotalPrices =
                                            int.parse(firstDataItem
                                                .originalPrice
                                                .toString());
                                        selected.selectedPotonganKupon =
                                            discountPriceRounded!;
                                        Provider.of<OrderProvider>(context,
                                                listen: false)
                                            .getTotalPrice(firstDataItem
                                                .finalPrice
                                                .toString());
                                        int? potonganKupon = (firstDataItem
                                                        .discountPrice !=
                                                    null &&
                                                firstDataItem.finalPrice != null
                                            ? discountPriceRounded -
                                                firstDataItem.finalPrice
                                            : null) as int?;
                                        int? potonganKupon2 =
                                            (firstDataItem.originalPrice !=
                                                        null &&
                                                    firstDataItem.finalPrice !=
                                                        null)
                                                ? int.parse(firstDataItem
                                                            .originalPrice ??
                                                        "0") -
                                                    int.parse(firstDataItem
                                                        .finalPrice
                                                        .toString())
                                                : null;
                                        selected.selectedPenguranganHarga =
                                            potonganKupon2!;
                                        if (firstDataItem.typeCoupon != "1")
                                          Navigator.of(context,
                                                  rootNavigator: true)
                                              .pushReplacement(
                                            MaterialPageRoute(
                                              builder: (context) =>
                                                  CheckoutDetailCoupon(
                                                idCart: [],
                                                potonganKupon: discountPriceRounded !=
                                                        0
                                                    ? (discountPriceRounded >
                                                            int.parse(
                                                                firstDataItem
                                                                    .finalPrice
                                                                    .toString())
                                                        ? potonganKupon
                                                        : discountPriceRounded)
                                                    : potonganKupon2,
                                                discountHarga:
                                                    firstDataItem.finalPrice,
                                                isKupon: true,
                                              ),
                                            ),
                                          );
                                        var token =
                                            await UsersInfo().getToken();
                                        if (firstDataItem.typeCoupon ==
                                            "1") if (token !=
                                                null ||
                                            Condition.loginFirebase == true) {
                                          if (await pay.freeCourseCoupon(
                                              int.parse(
                                                  firstDataItem.idCourse!),
                                              voucher)) {
                                            await Provider.of<MyCourseProvider>(
                                                    context,
                                                    listen: false)
                                                .getMyCourse();
                                            Navigator.pushReplacement(
                                              context,
                                              MaterialPageRoute(
                                                builder: (context) =>
                                                    SuccessFreeCourse(
                                                  id: firstDataItem.idCourse,
                                                  thumbnail:
                                                      firstDataItem.thubmnail,
                                                  title:
                                                      firstDataItem.courseName,
                                                  instructor:
                                                      firstDataItem.instructor,
                                                ),
                                              ),
                                            );
                                          } else {
                                            showNotifDialog(context);
                                          }
                                        } else {
                                          String teks = 'memiliki kursus ini';
                                          return _showDialogNotLogin();
                                        }

                                        kuponController.clear();
                                      } else {
                                        CherryToast.error(
                                          animationDuration: Durations.long1,
                                          title: Text(
                                              "Kupon tidak ditemukan pada kursus ini",
                                              style: TextStyle(
                                                color: Colors.black,
                                                fontSize: 15,
                                              )),
                                          animationType: AnimationType.fromTop,
                                        ).show(context);
                                      }
                                    },
                                    builder: (BuildContext context,
                                        TapDebouncerFunc? onTap) {
                                      return Padding(
                                        padding: EdgeInsets.only(
                                            bottom:
                                                getProportionateScreenHeight(
                                                    30)),
                                        child: DefaultButton(
                                            text: 'Tukarkan', press: onTap),
                                      );
                                    },
                                  ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      );
    }

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

    Widget buttonKuponWishlist() {
      return Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Consumer<detailCourseProv.DetailCourseProvider>(
            builder: (context, state, _) {
              if (state.state == detailCourseProv.ResultState.HasData) {
                var detailCourse = state.result!.data[0][0];
                if (detailCourse.isFreeCourse == '1') {
                  return SizedBox();
                } else {
                  if (widget.coupon == null) {
                    return Expanded(
                      child: (tokenCek == null)
                          ? Container(
                              margin: EdgeInsets.only(
                                  left: getProportionateScreenWidth(2)),
                              child: Transform.translate(
                                offset:
                                    Offset(getProportionateScreenWidth(110), 0),
                                child: GestureDetector(
                                  onTap: () {
                                    _showDialogNotLoginKupon();
                                  },
                                  child: Padding(
                                    padding: EdgeInsets.all(2.5),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        Text(""),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            )
                          : (iDuser == null)
                              ? Container(
                                  margin: EdgeInsets.only(
                                      left: getProportionateScreenWidth(2)),
                                  child: Padding(
                                      padding: EdgeInsets.all(2.5),
                                      child: Center(
                                        child: CircularProgressIndicator(),
                                      )),
                                )
                              : ('${detailCourse.instructorId}' == '$iDuser')
                                  ? Container(
                                      margin: EdgeInsets.only(
                                          left: getProportionateScreenWidth(2)),
                                      child: TapDebouncer(
                                        cooldown:
                                            const Duration(milliseconds: 3000),
                                        onTap: () async => await {
                                          CherryToast.error(
                                            animationDuration: Durations.long1,
                                            title: Text(
                                              "Anda tidak dapat menukarkan kupon di kursus anda sendiri",
                                              style: TextStyle(
                                                color: Colors.black,
                                                fontSize: 15,
                                              ),
                                            ),
                                            animationType:
                                                AnimationType.fromTop,
                                          ).show(context)
                                        },
                                        builder: (BuildContext context,
                                            TapDebouncerFunc? onTap) {
                                          return Transform.translate(
                                            offset: Offset(
                                                getProportionateScreenWidth(
                                                    110),
                                                0),
                                            child: GestureDetector(
                                              onTap: onTap,
                                              child: Padding(
                                                padding: EdgeInsets.all(2.5),
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.end,
                                                  children: [
                                                    SizedBox(width: 4),
                                                    Image.asset(
                                                      "assets/images/home_coupon.png",
                                                      color: primaryColor,
                                                    ),
                                                    SizedBox(width: 10),
                                                  ],
                                                ),
                                              ),
                                            ),
                                          );
                                        },
                                      ),
                                    )
                                  : (detailCourse.status_course != 'active')
                                      ? Container(
                                          margin: EdgeInsets.only(
                                              left: getProportionateScreenWidth(
                                                  2)),
                                          child: TapDebouncer(
                                            cooldown: const Duration(
                                                milliseconds: 3000),
                                            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 Transform.translate(
                                                offset: Offset(
                                                    getProportionateScreenWidth(
                                                        110),
                                                    0),
                                                child: GestureDetector(
                                                  onTap: onTap,
                                                  child: Padding(
                                                    padding:
                                                        EdgeInsets.all(2.5),
                                                    child: Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment.end,
                                                      children: [
                                                        SizedBox(width: 4),
                                                        Image.asset(
                                                          "assets/images/home_coupon.png",
                                                          color: primaryColor,
                                                        ),
                                                        SizedBox(width: 10),
                                                      ],
                                                    ),
                                                  ),
                                                ),
                                              );
                                            },
                                          ),
                                        )
                                      : (isAdmin == true)
                                          ? Container(
                                              margin: EdgeInsets.only(
                                                  left:
                                                      getProportionateScreenWidth(
                                                          2)),
                                              child: GestureDetector(
                                                onTap: () {},
                                                child: Transform.translate(
                                                  offset: Offset(
                                                      getProportionateScreenWidth(
                                                          110),
                                                      0),
                                                  child: Padding(
                                                    padding:
                                                        EdgeInsets.all(2.5),
                                                    child: Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment.end,
                                                      children: [
                                                        SizedBox(width: 4),
                                                        Image.asset(
                                                          "assets/images/home_coupon.png",
                                                          color: primaryColor,
                                                        ),
                                                        SizedBox(width: 1),
                                                      ],
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            )
                                          : Transform.translate(
                                              offset: Offset(
                                                  getProportionateScreenWidth(
                                                      110),
                                                  0),
                                              child: GestureDetector(
                                                onTap: () {
                                                  if (Condition.loginEmail ||
                                                      Condition.loginFirebase) {
                                                    _showKupon();
                                                  } else {
                                                    _showDialogNotLoginKupon();
                                                  }
                                                },
                                                child: Padding(
                                                  padding: EdgeInsets.symmetric(
                                                      vertical: 8),
                                                  child: Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.end,
                                                    children: [
                                                      Image.asset(
                                                        "assets/images/home_coupon.png",
                                                       color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode,
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            ),
                    );
                  } else {
                    return SizedBox.shrink();
                  }
                }
              } else {
                return const SizedBox();
              }
            },
          ),
          Consumer<detailCourseProv.DetailCourseProvider>(
              builder: (context, state, _) {
            if (state.state == detailCourseProv.ResultState.HasData) {
              var detailCourse = state.result!.data[0][0];
              if (detailCourse.isFreeCourse == '1') {
                return SizedBox();
              } else {
                return SizedBox(width: 12);
              }
            } else {
              return SizedBox();
            }
          }),
          Expanded(
            child: (iDuser == null)
                ? GestureDetector(
                    onTap: () {
                      _showDialogNotLogin();
                    },
                    child: !Condition.loginEmail && !Condition.loginFirebase
                        ? Padding(
                            padding: EdgeInsets.only(
                                right: getProportionateScreenWidth(10)),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                SvgPicture.asset(Theme.of(context).brightness ==
                                        Brightness.dark
                                    ? 'assets/icons/heart_dark.svg'
                                    : 'assets/icons/heart.svg'),
                              ],
                            ),
                          )
                        : Padding(
                            padding: EdgeInsets.all(2.5),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [CircularProgressIndicator()],
                            ),
                          ),
                  )
                : ('${widget.dataDetailCourseModel.instructorId}' == '$iDuser')
                    ? GestureDetector(
                        onTap: Provider.of<CartsProvider>(context)
                                .data
                                .contains(widget.dataDetailCourseModel.id)
                            ? checkUser
                            : wishlistExist,
                        child: !Condition.loginEmail && !Condition.loginFirebase
                            ? Row(
                                children: [
                                  Icon(
                                    Icons.favorite_border,
                                    color: Colors.white,
                                    size: getProportionateScreenWidth(18),
                                  ),
                                ],
                              )
                            : Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  Center(
                                    child: Consumer<
                                        wishlistProvider.WishlistProvider>(
                                      builder: (context, state, _) {
                                        if (state.state ==
                                            wishlistProvider
                                                .ResultState.Loading) {
                                          return SizedBox(
                                            height: 20,
                                            width: 20,
                                            child: CircularProgressIndicator(
                                              color: secondaryColor,
                                              strokeWidth: 1,
                                            ),
                                          );
                                        }
                                        return SvgPicture.asset(
                                          state.data.contains(widget
                                                  .dataDetailCourseModel.id)
                                              ? Theme.of(context).brightness ==
                                                      Brightness.dark
                                                  ? 'assets/icons/heart_dark_select.svg'
                                                  : 'assets/icons/heart_select.svg'
                                              : Theme.of(context).brightness ==
                                                      Brightness.dark
                                                  ? 'assets/icons/heart_dark.svg'
                                                  : 'assets/icons/heart.svg',
                                        );
                                      },
                                    ),
                                  ),
                                  SizedBox(
                                      width: getProportionateScreenWidth(6)),
                                  Center(
                                    child: Consumer<
                                        wishlistProvider.WishlistProvider>(
                                      builder: (contex, state, _) {
                                        if (state.state ==
                                            wishlistProvider
                                                .ResultState.Loading) {
                                          return Text('');
                                        }
                                        return Text(
                                          state.data.contains(widget
                                                  .dataDetailCourseModel.id)
                                              ? ''
                                              : '',
                                          overflow: TextOverflow.ellipsis,
                                          style: primaryTextStyle.copyWith(
                                            fontSize:
                                                getProportionateScreenWidth(12),
                                            letterSpacing: 0.2,
                                          ),
                                        );
                                      },
                                    ),
                                  ),
                                ],
                              ),
                      )
                    : (isAdmin == true)
                        ? GestureDetector(
                            onTap: () {
                              print('disabled admin');
                            },
                            child: !Condition.loginEmail &&
                                    !Condition.loginFirebase
                                ? Row(
                                    children: [
                                      Icon(
                                        Icons.favorite_border,
                                        color: Colors.white,
                                        size: getProportionateScreenWidth(18),
                                      ),
                                    ],
                                  )
                                : Row(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    children: [
                                      Center(
                                        child: Consumer<
                                            wishlistProvider.WishlistProvider>(
                                          builder: (context, state, _) {
                                            if (state.state ==
                                                wishlistProvider
                                                    .ResultState.Loading) {
                                              return SizedBox(
                                                height: 20,
                                                width: 20,
                                                child:
                                                    CircularProgressIndicator(
                                                  color: secondaryColor,
                                                  strokeWidth: 1,
                                                ),
                                              );
                                            }
                                            return SvgPicture.asset(
                                              state.data.contains(widget
                                                      .dataDetailCourseModel.id)
                                                  ? Theme.of(context)
                                                              .brightness ==
                                                          Brightness.dark
                                                      ? 'assets/icons/heart_dark_select.svg'
                                                      : 'assets/icons/heart_select.svg'
                                                  : Theme.of(context)
                                                              .brightness ==
                                                          Brightness.dark
                                                      ? 'assets/icons/heart_dark.svg'
                                                      : 'assets/icons/heart.svg',
                                            );
                                          },
                                        ),
                                      ),
                                      SizedBox(
                                          width:
                                              getProportionateScreenWidth(6)),
                                      Center(
                                        child: Consumer<
                                            wishlistProvider.WishlistProvider>(
                                          builder: (contex, state, _) {
                                            if (state.state ==
                                                wishlistProvider
                                                    .ResultState.Loading) {
                                              return Text('');
                                            }
                                            return Text(
                                              state.data.contains(widget
                                                      .dataDetailCourseModel.id)
                                                  ? ''
                                                  : '',
                                              overflow: TextOverflow.ellipsis,
                                              style: primaryTextStyle.copyWith(
                                                fontSize:
                                                    getProportionateScreenWidth(
                                                        12),
                                                letterSpacing: 0.2,
                                              ),
                                            );
                                          },
                                        ),
                                      ),
                                    ],
                                  ),
                          )
                        : (widget.dataDetailCourseModel.status_course ==
                                'prepublish')
                            ? GestureDetector(
                                onTap: Provider.of<CartsProvider>(context)
                                        .data
                                        .contains(
                                            widget.dataDetailCourseModel.id)
                                    ? checkUser
                                    : wishlistExist,
                                child: !Condition.loginEmail &&
                                        !Condition.loginFirebase
                                    ? Row(
                                        children: [
                                          Icon(
                                            Icons.favorite_border,
                                            color: Colors.white,
                                            size:
                                                getProportionateScreenWidth(18),
                                          ),
                                        ],
                                      )
                                    : Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.end,
                                        children: [
                                          Center(
                                            child: Consumer<
                                                wishlistProvider
                                                .WishlistProvider>(
                                              builder: (context, state, _) {
                                                if (state.state ==
                                                    wishlistProvider
                                                        .ResultState.Loading) {
                                                  return SizedBox(
                                                    height: 20,
                                                    width: 20,
                                                    child:
                                                        CircularProgressIndicator(
                                                      color: secondaryColor,
                                                      strokeWidth: 1,
                                                    ),
                                                  );
                                                }
                                                return SvgPicture.asset(
                                                  state.data.contains(widget
                                                          .dataDetailCourseModel
                                                          .id)
                                                      ? Theme.of(context)
                                                                  .brightness ==
                                                              Brightness.dark
                                                          ? 'assets/icons/heart_dark_select.svg'
                                                          : 'assets/icons/heart_select.svg'
                                                      : Theme.of(context)
                                                                  .brightness ==
                                                              Brightness.dark
                                                          ? 'assets/icons/heart_dark.svg'
                                                          : 'assets/icons/heart.svg',
                                                );
                                              },
                                            ),
                                          ),
                                          SizedBox(
                                              width:
                                                  getProportionateScreenWidth(
                                                      6)),
                                          Center(
                                            child: Consumer<
                                                wishlistProvider
                                                .WishlistProvider>(
                                              builder: (contex, state, _) {
                                                if (state.state ==
                                                    wishlistProvider
                                                        .ResultState.Loading) {
                                                  return Text('');
                                                }
                                                return Text(
                                                  state.data.contains(widget
                                                          .dataDetailCourseModel
                                                          .id)
                                                      ? ''
                                                      : '',
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style:
                                                      primaryTextStyle.copyWith(
                                                    fontSize:
                                                        getProportionateScreenWidth(
                                                            12),
                                                    letterSpacing: 0.2,
                                                  ),
                                                );
                                              },
                                            ),
                                          ),
                                        ],
                                      ),
                              )
                            : (widget.dataDetailCourseModel.status_course !=
                                    '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: !Condition.loginEmail &&
                                                !Condition.loginFirebase
                                            ? Row(
                                                children: [
                                                  Icon(
                                                    Icons.favorite_border,
                                                    color: Colors.white,
                                                    size:
                                                        getProportionateScreenWidth(
                                                            18),
                                                  ),
                                                ],
                                              )
                                            : Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.end,
                                                children: [
                                                  Center(
                                                    child: Consumer<
                                                        wishlistProvider
                                                        .WishlistProvider>(
                                                      builder:
                                                          (context, state, _) {
                                                        if (state.state ==
                                                            wishlistProvider
                                                                .ResultState
                                                                .Loading) {
                                                          return SizedBox(
                                                            height: 20,
                                                            width: 20,
                                                            child:
                                                                CircularProgressIndicator(
                                                              color:
                                                                  secondaryColor,
                                                              strokeWidth: 1,
                                                            ),
                                                          );
                                                        }
                                                        return SvgPicture.asset(
                                                          state.data.contains(widget
                                                                  .dataDetailCourseModel
                                                                  .id)
                                                              ? Theme.of(context)
                                                                          .brightness ==
                                                                      Brightness
                                                                          .dark
                                                                  ? 'assets/icons/heart_dark_select.svg'
                                                                  : 'assets/icons/heart_select.svg'
                                                              : Theme.of(context)
                                                                          .brightness ==
                                                                      Brightness
                                                                          .dark
                                                                  ? 'assets/icons/heart_dark.svg'
                                                                  : 'assets/icons/heart.svg',
                                                        );
                                                      },
                                                    ),
                                                  ),
                                                  SizedBox(
                                                    width:
                                                        getProportionateScreenWidth(
                                                            6),
                                                  ),
                                                  Center(
                                                    child: Consumer<
                                                        wishlistProvider
                                                        .WishlistProvider>(
                                                      builder:
                                                          (contex, state, _) {
                                                        if (state.state ==
                                                            wishlistProvider
                                                                .ResultState
                                                                .Loading) {
                                                          return Text('');
                                                        }
                                                        return Text(
                                                          state.data.contains(widget
                                                                  .dataDetailCourseModel
                                                                  .id)
                                                              ? ''
                                                              : '',
                                                          overflow: TextOverflow
                                                              .ellipsis,
                                                          style:
                                                              primaryTextStyle
                                                                  .copyWith(
                                                            fontSize:
                                                                getProportionateScreenWidth(
                                                                    12),
                                                            letterSpacing: 0.2,
                                                          ),
                                                        );
                                                      },
                                                    ),
                                                  ),
                                                ],
                                              ),
                                      );
                                    },
                                  )
                                : GestureDetector(
                                    onTap: Provider.of<
                                                wishlistProvider
                                                .WishlistProvider>(context)
                                            .data
                                            .contains(
                                                widget.dataDetailCourseModel.id)
                                        ? checkUser
                                        : wishlistExist,
                                    child: !Condition.loginEmail &&
                                            !Condition.loginFirebase
                                        ? Center(
                                            child: Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.end,
                                              children: [
                                                Icon(
                                                  Icons.favorite_border,
                                                  color: Colors.white,
                                                  size:
                                                      getProportionateScreenWidth(
                                                          18),
                                                ),
                                              ],
                                            ),
                                          )
                                        : Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.end,
                                            children: [
                                              Center(
                                                child: Consumer<
                                                    wishlistProvider
                                                    .WishlistProvider>(
                                                  builder: (context, state, _) {
                                                    if (state.state ==
                                                        wishlistProvider
                                                            .ResultState
                                                            .Loading) {
                                                      return SizedBox(
                                                        height: 20,
                                                        width: 20,
                                                        child:
                                                            CircularProgressIndicator(
                                                          color: secondaryColor,
                                                          strokeWidth: 1,
                                                        ),
                                                      );
                                                    }
                                                    return SvgPicture.asset(
                                                      state.data.contains(widget
                                                              .dataDetailCourseModel
                                                              .id)
                                                          ? Theme.of(context)
                                                                      .brightness ==
                                                                  Brightness
                                                                      .dark
                                                              ? 'assets/icons/heart_dark_select.svg'
                                                              : 'assets/icons/heart_select.svg'
                                                          : Theme.of(context)
                                                                      .brightness ==
                                                                  Brightness
                                                                      .dark
                                                              ? 'assets/icons/heart_dark.svg'
                                                              : 'assets/icons/heart.svg',
                                                    );
                                                  },
                                                ),
                                              ),
                                              SizedBox(
                                                  width:
                                                      getProportionateScreenWidth(
                                                          6)),
                                              Center(
                                                child: Consumer<
                                                    wishlistProvider
                                                    .WishlistProvider>(
                                                  builder: (contex, state, _) {
                                                    if (state.state ==
                                                        wishlistProvider
                                                            .ResultState
                                                            .Loading) {
                                                      return Text('');
                                                    }
                                                    return Text(
                                                      state.data.contains(widget
                                                              .dataDetailCourseModel
                                                              .id)
                                                          ? ''
                                                          : '',
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                      style: primaryTextStyle
                                                          .copyWith(
                                                        fontSize:
                                                            getProportionateScreenWidth(
                                                                12),
                                                        letterSpacing: 0.2,
                                                      ),
                                                    );
                                                  },
                                                ),
                                              ),
                                            ],
                                          ),
                                  ),
          ),
        ],
      );
    }

    initState() {
      super.initState();
      cekadmin();
    }

    return Stack(
      children: [
        Container(
          width: SizeConfig.screenWidth,
          child: Column(
            children: [
              imageCourse(),
              SizedBox(height: getProportionateScreenHeight(10)),
              Padding(
  padding: EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(15)),
  child: Row(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      // Expanded untuk menghindari overflow pada judul kursus
      Expanded(
        child: Text(
          widget.dataDetailCourseModel.title ?? ' ',
          style: thirdTextStyle.copyWith(
            fontSize: widget.dataDetailCourseModel.title!.length > 72
                ? getProportionateScreenWidth(13)
                : getProportionateScreenHeight(14),
            fontWeight: semiBold,
          ),
          maxLines: 3,
          overflow: TextOverflow.ellipsis, 
        ),
      ),

    
      SizedBox(width: getProportionateScreenWidth(10)),

      if (widget.coupon == null)
        widget.dataDetailCourseModel.isMine != 1
            ? Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  // Harga promo atau harga diskon
                  Text(
                    widget.dataDetailCourseModel.promoPrice != '0'
                        ? numberFormat(widget.dataDetailCourseModel.promoPrice)
                        : widget.dataDetailCourseModel.discountPrice == '0' &&
                                  widget.dataDetailCourseModel.price == '0'
                            ? 'Gratis'
                            : widget.dataDetailCourseModel.discountPrice == '0'
                                ? numberFormat(widget.dataDetailCourseModel.price)
                                : numberFormat(widget.dataDetailCourseModel.discountPrice),
                    style: thirdTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(15),
                      letterSpacing: 0.23,
                      fontWeight: semiBold,
                    ),
                  ),
                  SizedBox(height: getProportionateScreenHeight(3)),

                  // Harga asli yang dicoret jika ada diskon
                  if (widget.dataDetailCourseModel.promoPrice != '0' ||
                      widget.dataDetailCourseModel.discountPrice != '0')
                    Text(
                      numberFormat(widget.dataDetailCourseModel.price),
                      style: thirdTextStyle.copyWith(
                        fontSize: getProportionateScreenWidth(13),
                        letterSpacing: 0.23,
                        color: secondaryColor,
                        decoration: TextDecoration.lineThrough,
                      ),
                    ),
                ],
              )
            : SizedBox.shrink(),

      if (widget.coupon != null)
        widget.dataDetailCourseModel.isMine != 1
            ? Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    finalPriceCoupon.toString() == "0"
                        ? "Gratis"
                        : numberFormat(finalPriceCoupon.toString()),
                    style: thirdTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(15),
                      letterSpacing: 0.23,
                      fontWeight: semiBold,
                    ),
                  ),
                  SizedBox(height: getProportionateScreenHeight(3)),
                  Text(
                    finalPriceCoupon.toString() == "0"
                        ? "Gratis"
                        : numberFormat(widget.dataDetailCourseModel.price.toString()),
                    style: thirdTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(13),
                      letterSpacing: 0.23,
                      color: secondaryColor,
                      decoration: TextDecoration.lineThrough,
                    ),
                  ),
                ],
              )
            : SizedBox.shrink(),
    ],
  ),
),

              
              SizedBox(height: getProportionateScreenHeight(7)),
              MuridAndRating(
                  dataDetailCourseModel: widget.dataDetailCourseModel),
              Consumer<detailCourseProv.DetailCourseProvider>(
                builder: (context, state, _) {
                  if (state.state == detailCourseProv.ResultState.HasData) {
                    var detailCourse = state.result!.data[0][0];
                    if (detailCourse.isMine == 1) {
                      return SizedBox(height: getProportionateScreenHeight(30));
                    } else {
                      return Transform.translate(
                        offset: Offset(0, getProportionateScreenHeight(-30)),
                        child: buttonKuponWishlist(),
                      );
                    }
                  } else {
                    return Container();
                  }
                },
              ),
            ],
          ),
        ),
      ],
    );
  }
}
