import 'package:flutter/material.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/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 CourseBySubcategory extends StatefulWidget {
  CourseBySubcategory({
    Key? key,
    required this.name,
    required this.categoryId,
    required this.subId,
  }) : super(key: key);

  final String name;
  final String categoryId;
  final String subId;

  @override
  State<CourseBySubcategory> createState() => _CourseBySubcategoryState();
}

class _CourseBySubcategoryState extends State<CourseBySubcategory> {
  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: true,
            ),
            child: Container(
              child: Consumer<CourseByCategoryProvider>(
                  builder: (context, state, _) {
                if (state.state == ResultState.Loading) {
                  return Center(
                    child: CircularProgressIndicator(
                      color: secondaryColor,
                      strokeWidth: 2,
                    ),
                  );
                } else if (state.state == ResultState.HasData) {
                  return GestureDetector(
                    onTap: () {
                      setState(() {
                        _isExpanded = !_isExpanded;
                        _buttonPressed = !_buttonPressed;
                      });
                    },
                    child: Stack(
                      children: [
                        GestureDetector(
                          child: Container(
                            color: Colors.transparent,
                          ),
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            AppBarFilter(),
                            SizedBox(height: getProportionateScreenHeight(10)),
                            Container(
                              margin: EdgeInsets.symmetric(
                                  horizontal: getProportionateScreenWidth(16)),
                              child: Text(
                                '${widget.name}',
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(20),
                                  letterSpacing: -0.5,
                                  fontWeight: bold,
                                ),
                                textAlign: TextAlign.start,
                              ),
                            ),
                            SizedBox(height: getProportionateScreenHeight(20)),
                            Container(
                              margin: EdgeInsets.symmetric(
                                  horizontal: getProportionateScreenWidth(16)),
                              child: Text(
                                "Semua Kursus ${widget.name}",
                                style:
                                    thirdTextStyle.copyWith(fontWeight: bold),
                              ),
                            ),
                            SizedBox(height: getProportionateScreenHeight(20)),
                            GridView.builder(
                              padding: EdgeInsets.only(
                                right: getProportionateScreenWidth(22),
                                left: getProportionateScreenWidth(7),
                              ),
                              physics: ScrollPhysics(),
                              shrinkWrap: true,
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 2,
                                childAspectRatio: 2.8 / 4,
                                crossAxisSpacing: 16,
                                mainAxisSpacing: 12,
                              ),
                              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(17)),
                                  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,
                                          ),
                                        ),
                                      );
                                    },
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                      ],
                    ),
                  );
                } else if (state.state == ResultState.NoData) {
                  return Stack(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          AppBarHeader(),
                          Container(
                            margin: EdgeInsets.symmetric(
                                horizontal: getProportionateScreenWidth(16)),
                            child: Text(
                              '${widget.name.replaceAll('&amp;', '&')}',
                              style: secondaryTextStyle.copyWith(
                                fontSize: getProportionateScreenWidth(25),
                                letterSpacing: -0.5,
                              ),
                              textAlign: TextAlign.start,
                            ),
                          ),
                        ],
                      ),
                      Center(
                        child: Padding(
                          padding: EdgeInsets.only(
                              top: getProportionateScreenHeight(300)),
                          child: Text(
                            "Sub kategori yang dipilih tidak memiliki kursus",
                            style: TextStyle(
                                fontSize: getProportionateScreenWidth(10)),
                          ),
                        ),
                      ),
                    ],
                  );
                } else if (state.state == ResultState.Error) {
                  return Center(child: Text("Terjadi kesalahan."));
                } else {
                  return Center(child: Text(''));
                }
              }),
            ),
          ),
        ),
      ),
    );
  }

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