import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:initial_folder/helper/validator.dart';
import 'package:initial_folder/providers/course_by_category_provider.dart';
import 'package:initial_folder/screens/detail_course/components/app_bar.dart';
import 'package:initial_folder/screens/detail_course/components/app_bar_filter.dart';
import 'package:initial_folder/screens/detail_course/detail_course_screen.dart';
import 'package:initial_folder/screens/home/components/body_comp/latest_course.dart';
import 'package:initial_folder/screens/home/components/body_comp/list_of_categories.dart';
import 'package:initial_folder/screens/home/components/body_comp/populer_course.dart';
import 'package:initial_folder/screens/home/components/body_comp/product_card/product_card.dart';
import 'package:initial_folder/services/course_by_category_service.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/custom_navigator.dart';
import 'package:provider/provider.dart';

class CourseByCategory extends StatefulWidget {
  CourseByCategory({
    Key? key,
    required this.name,
    required this.categoryId,
    required this.subId,
    this.homeCategories,
  }) : super(key: key);

  final String name;
  final String categoryId;
  final String subId;
  final bool? homeCategories;

  @override
  State<CourseByCategory> createState() => _CourseByCategoryState();
}

class _CourseByCategoryState extends State<CourseByCategory> {
  bool _isExpanded = false;
  bool _buttonPressed = false;
  final ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: SingleChildScrollView(
          controller: _scrollController,
          child: ChangeNotifierProvider<CourseByCategoryProvider>(
            create: (context) => CourseByCategoryProvider(
              courseByCategoryService: CourseByCategoryService(),
              id: widget.categoryId,
              subId: widget.subId,
              fetchBySubcategory: false,
            ),
            child: Container(
              child: Consumer<CourseByCategoryProvider>(
                  builder: (context, state, _) {
                if (state.state == ResultState.Loading) {
                  return Center(
                    child: Padding(
                      padding: EdgeInsets.only(
                          top: getProportionateScreenHeight(300)),
                      child: CircularProgressIndicator(
                        color: secondaryColor,
                        strokeWidth: 2,
                      ),
                    ),
                  );
                } else if (state.state == ResultState.HasData) {
                  return Stack(
                    children: [
                      GestureDetector(
                        child: Container(
                          color: Colors.transparent,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            _isExpanded = !_isExpanded;
                            _buttonPressed = !_buttonPressed;
                          });
                        },
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            AppBarHeader(),
                            SizedBox(height: getProportionateScreenHeight(23)),
                            Container(
                              margin: EdgeInsets.symmetric(
                                  horizontal: getProportionateScreenWidth(19)),
                              child: Text(
                                '${widget.name.replaceAll('&amp;', '&')}',
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(20),
                                  letterSpacing: -0.5,
                                  fontWeight: FontWeight.w600,
                                ),
                                textAlign: TextAlign.start,
                              ),
                            ),
                            if (widget.homeCategories == null)
                              SizedBox(
                                  height: getProportionateScreenHeight(65)),
                            if (widget.homeCategories == null)
                              PopulerCourse(text: 'Populer'),
                            if (widget.homeCategories == null)
                              LatestCourse(text: "New Release"),
                            if (widget.homeCategories == null)
                              SizedBox(
                                  height: getProportionateScreenHeight(15)),
                            if (widget.homeCategories != null)
                              SizedBox(
                                  height: getProportionateScreenHeight(25)),
                            if (widget.homeCategories == null)
                              Padding(
                                padding: EdgeInsets.only(
                                  left: getProportionateScreenWidth(16),
                                  bottom: getProportionateScreenHeight(28),
                                ),
                                child: Text(
                                  "${widget.name}",
                                  textAlign: TextAlign.left,
                                  style: thirdTextStyle.copyWith(
                                    letterSpacing: 1,
                                    fontSize: getProportionateScreenWidth(15),
                                    fontWeight: semiBold,
                                  ),
                                ),
                              ),
                            GridView.builder(
                              padding: EdgeInsets.only(
                                right: getProportionateScreenWidth(21),
                                left: getProportionateScreenWidth(7),
                                bottom: getProportionateScreenHeight(18),
                              ),
                              physics: ScrollPhysics(),
                              shrinkWrap: true,
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 2,
                                childAspectRatio: 2.8 / 4,
                                crossAxisSpacing: 16,
                                mainAxisSpacing: 14,
                              ),
                              itemCount: state.result.length,
                              itemBuilder: (context, index) {
                                var courses = state.result[index];
                                int price = int.tryParse(
                                        courses.price.replaceAll('.', '')) ??
                                    0;
                                int discountPrice = int.tryParse(courses
                                        .discountPrice
                                        .replaceAll('.', '')) ??
                                    0;

                                int calculatedPrice =
                                    (courses.discountPrice != '0')
                                        ? price - discountPrice
                                        : price;
                                String displayedPrice = (calculatedPrice == 0)
                                    ? courses.price
                                    : calculatedPrice.toString();

                                return Container(
                                  margin: EdgeInsets.only(
                                      bottom: getProportionateScreenHeight(13)),
                                  child: ProductCard(
                                    totalDiscount: courses.totalDiscount ?? 0,
                                    students: courses.students ?? '0',
                                    id: courses.idCourse,
                                    thumbnail: courses.thumbnail ??
                                        'https://vocasia.id/uploads/thumbnails/course_thumbnails/course_thumbnail_default_63.jpg',
                                    title: courses.title,
                                    instructorName: courses.instructorName,
                                    specificRating: double.parse(courses
                                                    .rating[0]!.avgRating !=
                                                null
                                            ? '${courses.rating[0]!.avgRating}'
                                            : '5.0')
                                        .toString(),
                                    rating: courses.rating[0]!.avgRating != null
                                        ? '${courses.rating[0]!.avgRating}'
                                        : '5.0',
                                    numberOfRatings:
                                        courses.rating[0]!.totalReview ?? '0',
                                    isTopCourse: '0',
                                    price: (courses.discountPrice == '0')
                                        ? 'Gratis'
                                        : numberFormat(displayedPrice),
                                    realPrice: (courses.price == '0')
                                        ? ''
                                        : numberFormat(courses.price),
                                    press: () async {
                                      Navigator.of(context, rootNavigator: true)
                                          .push(
                                        CustomNavigator(
                                          child: DetailCourseScreen(
                                            idcourse: courses.idCourse,
                                          ),
                                        ),
                                      );
                                    },
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                      ),
                      if (widget.homeCategories == null)
                        Positioned.fill(
                          child: FractionallySizedBox(
                            alignment: Alignment.topLeft,
                            widthFactor: 1,
                            heightFactor: 1,
                            child: Padding(
                              padding: EdgeInsets.only(
                                  top: getProportionateScreenHeight(87)),
                              child: Categories(
                                selectedCategoryId: widget.categoryId,
                                key: UniqueKey(),
                                scrollController: _scrollController,
                              ),
                            ),
                          ),
                        ),
                    ],
                  );
                } else if (state.state == ResultState.NoData) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      AppBarHeader(),
                      Container(
                        margin: EdgeInsets.symmetric(
                            horizontal: getProportionateScreenWidth(16)),
                        child: Text(
                          '${widget.name.replaceAll('&amp;', '&')}',
                          style: thirdTextStyle.copyWith(
                            fontSize: getProportionateScreenWidth(25),
                            letterSpacing: -0.5,
                            fontWeight: FontWeight.bold,
                          ),
                          textAlign: TextAlign.start,
                        ),
                      ),
                      Categories(
                        selectedCategoryId: widget.categoryId,
                        key: UniqueKey(),
                        scrollController: _scrollController,
                      ),
                      SizedBox(height: getProportionateScreenHeight(200)),
                      Center(
                        child: Text(
                          "Oops! Tidak ada kursus yang tersedia dalam kategori ini.",
                          textAlign: TextAlign.center,
                          style: thirdTextStyle.copyWith(
                            fontSize: getProportionateScreenWidth(14),
                            color: Colors.grey,
                          ),
                        ),
                      ),
                      SizedBox(height: getProportionateScreenHeight(60)),
                    ],
                  );
                } else if (state.state == ResultState.Error) {
                  return Center(child: Text("No internet connections."));
                } else {
                  return Center(child: Text(''));
                }
              }),
            ),
          ),
        ),
      ),
    );
  }

  void _collapseSubcategories() {
    _scrollController.animateTo(
      0,
      duration: Duration(milliseconds: 500),
      curve: Curves.easeInOut,
    );
  }
}
