import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/providers/banners_provider.dart';
import 'package:initial_folder/providers/carts_provider.dart';
import 'package:initial_folder/providers/categories_provider.dart';
import 'package:initial_folder/providers/course_by_category_provider.dart';
import 'package:initial_folder/providers/detail_course_provider.dart';
import 'package:initial_folder/providers/latest_course_provider.dart';
import 'package:initial_folder/providers/lesson_course_provider.dart';
import 'package:initial_folder/providers/others_course_provider.dart';
import 'package:initial_folder/providers/promo_course_provider.dart';
import 'package:initial_folder/providers/promo_course_provider.dart' as promo;
import 'package:initial_folder/providers/top_course_provider.dart';
import 'package:initial_folder/screens/cart/cart_page.dart';
import 'package:initial_folder/screens/course/play_course_page.dart';
import 'package:initial_folder/screens/home/components/appBar/home_header.dart';
import 'package:initial_folder/screens/home/components/body_comp/certificate_voucher.dart';
import 'package:initial_folder/screens/home/components/body_comp/course_by_category.dart';
import 'package:initial_folder/screens/home/components/body_comp/home_categories.dart';
import 'package:initial_folder/screens/home/components/body_comp/latest_course.dart';
import 'package:initial_folder/screens/home/components/body_comp/lihat_semua_kategori.dart';
import 'package:initial_folder/screens/home/components/body_comp/populer_course.dart';
import 'package:initial_folder/screens/home/components/body_comp/promo_course.dart';
import 'package:initial_folder/services/categories_service.dart';
import 'package:initial_folder/services/course_by_category_service.dart';
import 'package:initial_folder/services/course_service.dart';
import 'package:initial_folder/services/lesson_course_service.dart';
import 'package:provider/provider.dart';
import '../../../size_config.dart';
import '../../../theme.dart';
import 'body_comp/others_course.dart';
import 'body_comp/carousel.dart';


class HomePage extends StatefulWidget {
  static String routeName = "/homepage";
  HomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  ScrollController _controller = ScrollController();
  GlobalKey<NavigatorState> homeKey = GlobalKey<NavigatorState>();
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<CartsProvider>(context, listen: false).getCarts();
    });
    _controller.addListener(() {
      onScrol();
    });
    super.initState();

    FirebaseMessaging.instance.getInitialMessage().then((message) {
      if (message?.data['route'] == "/cart") {
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => CartPage(),
            ));
      } else if (message?.data['route'] == "/play_course") {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => MultiProvider(
              providers: [
                ChangeNotifierProvider(
                  create: (context) => LessonCourseProvider(
                    lessonCourseService: LessonCourseService(),
                    id: int.parse(message?.data['id_course'] ?? '0'),
                  ),
                ),
                ChangeNotifierProvider(
                    create: (context) => DetailCourseProvider(
                        courseService: CourseService(),
                        id: message?.data['id_course'] ?? '1'))
              ],
              child: PlayCourse(
                judul: message?.data['title'] ?? '',
                instruktur: message?.data['instructur_name'] ?? '',
                thumbnail: message?.data['thumbnail'] ??
                    '$baseUrl/uploads/courses_thumbnail/course_thumbnail_default_57.jpg',
                courseeid: message?.data['id_course'] ?? '',
                isQna: true,
              ),
            ),
          ),
        );
      }
    });
  }

  void onScrol() async {
    double maxScroll = _controller.position.maxScrollExtent;
    double currentScroll = _controller.position.pixels;
    if (maxScroll == currentScroll) {
      await Provider.of<OthersCourseProvider>(context, listen: false)
          .getOthersCourses();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void onRefresh() async {
    Provider.of<OthersCourseProvider>(context, listen: false)
        .getOthersCourses();
    Provider.of<BannersProvider>(context, listen: false).getAllBanners();
    Provider.of<PromoCourseProvider>(context, listen: false).getPromoCourse();
    Provider.of<TopCourseProvider>(context, listen: false).getTopCourse();
    Provider.of<LatestCourseProvider>(context, listen: false).getLatestCourse();
    Provider.of<OthersCourseProvider>(context, listen: false).getOthersCourse();
    setState(() {
      print('Reloading page...');
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_controller.hasClients) {
      if (_controller.position.pixels != _controller.position.maxScrollExtent) {
        _controller.animateTo(0,
            duration: Duration(milliseconds: 900), curve: Curves.linear);
      }
    }
    return Navigator(
      key: homeKey,
      onGenerateRoute: (RouteSettings settings) {
        return MaterialPageRoute(
          settings: settings,
          builder: (BuildContext context) {
            if (settings.name == '/lihatSemuaKategori') {
              return LihatSemuaKategori();
            }

            return Container(
              color: Theme.of(context).colorScheme.background,
              child: SafeArea(
                child: Scaffold(
                  backgroundColor: Theme.of(context).colorScheme.background,
                  appBar: PreferredSize(
                    preferredSize:
                        Size.fromHeight(getProportionateScreenHeight(60)),
                    child: HomeHeader(),
                  ),
                  body: RefreshIndicator(
                    onRefresh: () async {
                      setState(() {
                        print('loding test');
                        onRefresh();
                      });
                    },
                    child: ListView(
                      controller: _controller,
                      children: [
                        SizedBox(height: getProportionateScreenHeight(10)),
                        // Stack(
                        //   children: [
                        //     // Container(
                        //     //   height: getProportionateScreenWidth(140),
                        //     //   decoration: BoxDecoration(
                        //     //     image: DecorationImage(
                        //     //       image: AssetImage('assets/images/VectorBG.png'),
                        //     //       fit: BoxFit.fill,
                        //     //       alignment: AlignmentDirectional.topCenter,
                        //     //     ),
                        //     //   ),
                        //     // ),
                        //     Container(
                        //         padding: EdgeInsets.fromLTRB(
                        //             getProportionateScreenWidth(18.0),
                        //             getProportionateScreenWidth(11.5),
                        //             0,
                        //             0),
                        //         child: Begin()),
                        //     SizedBox(height: getProportionateScreenWidth(24)),
                        //     Container(
                        //       // padding:
                        //       //     EdgeInsets.only(top: getProportionateScreenWidth(110)),
                        //       //height: getProportionateScreenWidth(33),
                        //       alignment: Alignment.bottomCenter,
                        //       child: SearchField(),
                        //     ),
                        //   ],
                        // ),
                        // Container(
                        //     padding: EdgeInsets.fromLTRB(getProportionateScreenWidth(18.0),
                        //         getProportionateScreenWidth(11.5), 0, 0),
                        //     child: Begin()),
                        // SizedBox(height: getProportionateScreenWidth(36)),

                        //SearchField(),

                        // SizedBox(height: getProportionateScreenWidth(12)),
                        CarouselWithIndicatorDemo(),

                        // Padding(
                        //   padding: EdgeInsets.symmetric(
                        //       horizontal: getProportionateScreenWidth(14)),
                        //   child: Center(child: GopayVoucher()),
                        // ),
                        // SizedBox(height: 18),
                        // Program(),
                        HomeCategories(),
                        Padding(
                          padding: EdgeInsets.symmetric(
                              horizontal: getProportionateScreenWidth(14)),
                          child: CertificateVoucher(),
                        ),
                        SizedBox(height: getProportionateScreenHeight(19)),
                        // Padding(
                        //   padding: EdgeInsets.symmetric(
                        //       horizontal: getProportionateScreenWidth(20)),
                        //   child:
                        //       Row(mainAxisAlignment: MainAxisAlignment.start, children: [
                        //     Text('Pencarian Terpopuler',
                        //         textAlign: TextAlign.left,
                        //         style: secondaryTextStyle.copyWith(
                        //             letterSpacing: 1,
                        //             color: tenthColor,
                        //             fontSize: getProportionateScreenWidth(14),
                        //             fontWeight: semiBold)),
                        //   ]),
                        // ),
                        // SizedBox(height: 10),
                        // Categories(),
                        Consumer<PromoCourseProvider>(
                          builder: (context, promoState, _) {
                           SizedBox(height: 20);
                            return promoState.state == promo.ResultState.HasData
                                ? PromoCourse(text: "Promo")
                                : SizedBox();
                          },
                        ),

                        SizedBox(height: 20),

                        PopulerCourse(text: "Kursus Teratas"),
                        LatestCourse(text: "Kursus Terbaru"),
                        SizedBox(height: getProportionateScreenHeight(25)),
                        OthersCourse(),
                        Provider.of<OthersCourseProvider>(context).loading
                            ? Center(
                                child: SizedBox(
                                  height: 30,
                                  width: 30,
                                  child: CircularProgressIndicator(
                                    color: secondaryColor,
                                    strokeWidth: 2,
                                  ),
                                ),
                              )
                            : SizedBox(height: 30),
                        SizedBox(height: 25),
                        // ChangeNotifierProvider<CourseProvider>.value(
                        //     value: CourseProvider(courseService: CourseService()),
                        //     child: Course()),

                        // Recommendation(),
                      ],
                    ),
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }
}
