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/detail_course_screen.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:provider/provider.dart';

class CourseTerkait extends StatefulWidget {
  CourseTerkait({
    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<CourseTerkait> createState() => _CourseTerkaitState();
}

class _CourseTerkaitState extends State<CourseTerkait> {
  final ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return 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: CircularProgressIndicator(
                      color: primaryColor,
                      strokeWidth: 2,
                    ),
                  );
                } else if (state.state == ResultState.HasData) {
                  return Stack(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              SizedBox(
                                  height: getProportionateScreenHeight(13)),
                              Text(
                                '  Kursus Terkait',
                                style: thirdTextStyle.copyWith(
                                  fontWeight: semiBold,
                                  fontSize: getProportionateScreenWidth(15),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(20)),
                          GridView.builder(
                            padding: EdgeInsets.only(
                              right: getProportionateScreenWidth(21),
                              left: getProportionateScreenWidth(7),
                              bottom: getProportionateScreenHeight(18),
                            ),
                            physics: BouncingScrollPhysics(),
                            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.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) =>
                                            DetailCourseScreen(
                                          idcourse: courses.idCourse,
                                        ),
                                      ),
                                    );
                                  },
                                ),
                              );
                            },
                          ),
                          SizedBox(height: getProportionateScreenHeight(50)),
                        ],
                      ),
                    ],
                  );
                } else if (state.state == ResultState.NoData) {
                  return Center(child: Text("Tidak ada kursus terkait"));
                } else if (state.state == ResultState.Error) {
                  return Center(child: Text("No internet connections."));
                } else {
                  return Center(child: Text(''));
                }
              },
            ),
          ),
        ),
      ),
    );
  }
}
