import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/helper/validator.dart';
import 'package:initial_folder/providers/search_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/screens/search_course/component/filter.dart';
import 'package:initial_folder/widgets/custom_navigator.dart';
import 'package:initial_folder/widgets/search_not_found.dart';
import 'package:provider/provider.dart';
import '../providers/theme_provider.dart';
import '../size_config.dart';
import '../theme.dart';
import 'package:initial_folder/providers/filters_course_provider.dart'
    as filterCourseProvider;

class SearchAndFilterCourse extends StatefulWidget {
  const SearchAndFilterCourse({
    Key? key,
  }) : super(key: key);
  static const routeName = '/search-and-filter';

  @override
  State<SearchAndFilterCourse> createState() => _SearchAndFilterCourseState();
}

class _SearchAndFilterCourseState extends State<SearchAndFilterCourse> {
  final TextEditingController _controller = TextEditingController();

  void clearTextField() {
    _controller.clear();
  }

  @override
  void initState() {
    super.initState();
    Provider.of<SearchProvider>(context, listen: false).resetState();
    Provider.of<filterCourseProvider.FilterCourseProvider>(context,
            listen: false)
        .resetState();
    Provider.of<filterCourseProvider.FilterCourseProvider>(context,
            listen: false)
        .resetFilter();
  }

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);
    return Scaffold(
      backgroundColor: Theme.of(context).colorScheme.background,
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(getProportionateScreenWidth(57)),
        child: AppBar(
          scrolledUnderElevation: 0,
          backgroundColor: Theme.of(context).colorScheme.background,
          leadingWidth: 30,
          actions: [
            IconButton(
              padding: EdgeInsets.zero,
              onPressed: () => Navigator.of(context, rootNavigator: true).push(
                CustomNavigator(
                  child: Filter(
                    onApplyFilter: clearTextField,
                  ),
                ),
              ),
              icon: Icon(
                Icons.tune_rounded,
                color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode, 
              ),
            ),
          ],
          title: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: Theme.of(context).brightness == Brightness.dark
                  ? seventeenColor
                  : secondaryColor.withOpacity(0.3),
            ),
            height: 40,
            child: Consumer<SearchProvider>(
              builder: (context, state, _) => TextField(
                controller: _controller,
                autofocus: false,
                onSubmitted: (value) async {
                  Provider.of<filterCourseProvider.FilterCourseProvider>(
                          context,
                          listen: false)
                      .isSearchsFalse();
                  filterCourseProvider.FilterCourseProvider filterCourseProv =
                      Provider.of<filterCourseProvider.FilterCourseProvider>(
                          context,
                          listen: false);

                  state.searchTextFilter = "";
                  state.searchText = validatorSearch(value);
                  await state.initSearchCourse(
                    price: filterCourseProv.currentIndexPrice,
                    level: filterCourseProv.levels.join(','),
                    rating: filterCourseProv.currentIndexRating,
                  );
                },
                style: primaryTextStyle.copyWith(
                  fontSize: getProportionateScreenWidth(14),
                  letterSpacing: 0.5,
                ),
                onChanged: (value) {
                  state.searchTextFilter = ""; 
                  state.searchText = validatorSearch(value);
                },
                cursorColor: secondaryColor,
                decoration: InputDecoration(
                  border: InputBorder.none,
                  errorBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: sevenColor),
                      borderRadius: BorderRadius.circular(10)),
                  contentPadding:
                      EdgeInsets.only(top: getProportionateScreenHeight(4)),
                  prefixIcon: Icon(
                    FeatherIcons.search,
                    size: 20,
                    color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode, 
                  ),
                  hintText: 'Cari Kursus',
                  hintStyle: primaryTextStyle.copyWith(
                    fontSize: getProportionateScreenWidth(12),
                    color: secondaryColor,
                    letterSpacing: 0.5,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
      body: Provider.of<filterCourseProvider.FilterCourseProvider>(context)
              .isSearch
          ? Consumer<filterCourseProvider.FilterCourseProvider>(
              builder: (context, state, _) {
                SearchProvider searchProvider =
                    Provider.of<SearchProvider>(context, listen: false);
                print("Ini searchan ${searchProvider.search}");
                if (state.state == filterCourseProvider.ResultState.loading) {
                  return Center(
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      color: Colors.green,
                    ),
                  );
                } else if (state.state ==
                    filterCourseProvider.ResultState.hasData) {
                  return Padding(
                    padding:
                        EdgeInsets.only(left: getProportionateScreenWidth(2)),
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Padding(
                            padding: EdgeInsets.only(
                              left: getProportionateScreenWidth(14),
                              top: getProportionateScreenHeight(5),
                            ),
                            child: Text(
                              "Kursus ${searchProvider.searchTextFilter.replaceAll('%', ' ')}",
                              textAlign: TextAlign.left,
                              style: thirdTextStyle.copyWith(
                                letterSpacing: 1,
                                fontSize: getProportionateScreenWidth(15),
                                fontWeight: semiBold,
                              ),
                            ),
                          ),
                          GridView.builder(
                            padding: EdgeInsets.only(
                              right: getProportionateScreenWidth(20),
                              top: getProportionateScreenHeight(20),
                              bottom: getProportionateScreenHeight(20),
                            ),
                            physics: ScrollPhysics(),
                            shrinkWrap: true,
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 2,
                              childAspectRatio: 2.8 / 4,
                              crossAxisSpacing: 10,
                              mainAxisSpacing: 13,
                            ),
                            itemCount: state.filterResult.length,
                            itemBuilder: (context, index) {
                              var course = state.filterResult[index];
                              int price = int.tryParse(
                                      course.price.replaceAll('.', '')) ??
                                  0;
                              int discountPrice = int.tryParse(course
                                      .discountPrice
                                      .replaceAll('.', '')) ??
                                  0;

                              int calculatedPrice =
                                  (course.discountPrice != '0')
                                      ? price - discountPrice
                                      : price;

                              String displayedPrice = (calculatedPrice == 0)
                                  ? course.price
                                  : calculatedPrice.toString();
                              return Container(
                                margin: EdgeInsets.only(
                                    bottom: getProportionateScreenHeight(11)),
                                child: ProductCard(
                                  totalDiscount: course.totalDiscount ?? 0,
                                  students: course.students ?? '0',
                                  id: course.idCourse,
                                  thumbnail: course.thumbnail ??
                                      '$baseUrl/uploads/courses_thumbnail/course_thumbnail_default_57.jpg',
                                  title: course.title,
                                  instructorName: course.instructorName,
                                  specificRating: double.parse(
                                          course.rating[0]!.avgRating != null
                                              ? '${course.rating[0]!.avgRating}'
                                              : '5.0')
                                      .toString(),
                                  rating: course.rating[0]!.avgRating != null
                                      ? '${course.rating[0]!.avgRating}'
                                      : '5.0',
                                  numberOfRatings:
                                      course.rating[0]!.totalReview ?? '0',
                                  isTopCourse: course.topCourse ?? '0',
                                  price: (course.price == '0')
                                      ? 'Gratis'
                                      : (course.promoPrice != '0')
                                          ? numberFormat(course.promoPrice)
                                          : numberFormat(displayedPrice),
                                  realPrice: (course.price == '0')
                                      ? ''
                                      : numberFormat(course.price),
                                  press: () {
                                    Navigator.of(context, rootNavigator: true)
                                        .push(
                                      CustomNavigator(
                                        child: DetailCourseScreen(
                                          idcourse: course.idCourse,
                                        ),
                                      ),
                                    );
                                  },
                                ),
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  );
                } else if (state.state ==
                        filterCourseProvider.ResultState.error ||
                    state.state == filterCourseProvider.ResultState.noData) {
                  return SearchNotFound();
                } else {
                  return Center(child: Text(''));
                }
              },
            )
          : Consumer<SearchProvider>(
              builder: (context, state, _) {
                SearchProvider searchProvider =
                    Provider.of<SearchProvider>(context, listen: false);

                if (state.state == ResultState.loading) {
                  return Center(
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      color: primaryColor,
                    ),
                  );
                } else if (state.state == ResultState.hasData) {
                  return Padding(
                    padding:
                        EdgeInsets.only(left: getProportionateScreenWidth(2)),
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Padding(
                            padding: EdgeInsets.only(
                              left: getProportionateScreenWidth(14),
                              top: getProportionateScreenHeight(5),
                            ),
                            child: searchProvider.searchText.isNotEmpty
                                ? Text(
                                    "Kursus ${searchProvider.searchText.replaceAll('%', ' ')}",
                                    textAlign: TextAlign.left,
                                    style: thirdTextStyle.copyWith(
                                      letterSpacing: 1,
                                      fontSize: getProportionateScreenWidth(15),
                                      fontWeight: semiBold,
                                    ),
                                  )
                                : Text(
                                    "Kursus ${searchProvider.searchTextFilter.replaceAll('%', ' ')}",
                                    textAlign: TextAlign.left,
                                    style: thirdTextStyle.copyWith(
                                      letterSpacing: 1,
                                      fontSize: getProportionateScreenWidth(15),
                                      fontWeight: semiBold,
                                    ),
                                  ),
                          ),
                          GridView.builder(
                            padding: EdgeInsets.only(
                              right: getProportionateScreenWidth(20),
                              top: getProportionateScreenHeight(20),
                              bottom: getProportionateScreenHeight(20),
                            ),
                            physics: ScrollPhysics(),
                            shrinkWrap: true,
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 2,
                              childAspectRatio: 2.8 / 4,
                              crossAxisSpacing: 12,
                              mainAxisSpacing: 18,
                            ),
                            itemCount: state.result.length,
                            itemBuilder: (context, index) {
                              var othersCourse = state.result[index];

                              int price = int.tryParse(
                                      othersCourse.price.replaceAll('.', '')) ??
                                  0;
                              int discountPrice = int.tryParse(othersCourse
                                      .discountPrice
                                      .replaceAll('.', '')) ??
                                  0;

                              int calculatedPrice =
                                  (othersCourse.discountPrice != '0')
                                      ? price - discountPrice
                                      : price;

                              String displayedPrice = (calculatedPrice == 0)
                                  ? othersCourse.price.toString()
                                  : calculatedPrice.toString();
                              return Container(
                                margin: EdgeInsets.only(
                                    bottom: getProportionateScreenHeight(11)),
                                child: ProductCard(
                                  totalDiscount:
                                      othersCourse.totalDiscount ?? 0,
                                  students: othersCourse.students ?? '0',
                                  id: othersCourse.idCourse,
                                  thumbnail: othersCourse.thumbnail ??
                                      '$baseUrl/uploads/courses_thumbnail/course_thumbnail_default_57.jpg',
                                  title: othersCourse.title,
                                  instructorName: othersCourse.instructorName,
                                  specificRating: (othersCourse
                                              .rating.isNotEmpty &&
                                          othersCourse.rating[0]?.avgRating !=
                                              null)
                                      ? othersCourse.rating[0]!.avgRating
                                          .toString()
                                      : '0',
                                  rating: (othersCourse.rating.isNotEmpty &&
                                          othersCourse.rating[0]?.avgRating !=
                                              null)
                                      ? othersCourse.rating[0]!.avgRating
                                          .toString()
                                      : '5.0',
                                  numberOfRatings: (othersCourse
                                              .rating.isNotEmpty &&
                                          othersCourse.rating[0]?.totalReview !=
                                              null)
                                      ? othersCourse.rating[0]!.totalReview!
                                      : '0',
                                  isTopCourse: othersCourse.topCourse ?? '0',
                                  price: (othersCourse.price == '0')
                                      ? 'Gratis'
                                      : (othersCourse.promoPrice != '0')
                                          ? numberFormat(
                                              othersCourse.promoPrice)
                                          : numberFormat(displayedPrice),
                                  realPrice: (othersCourse.price == '0')
                                      ? ''
                                      : numberFormat(
                                          othersCourse.price.toString()),
                                  press: () {
                                    print('ini ke detail');
                                    if (othersCourse.promoPrice != '0') {
                                      Navigator.of(context, rootNavigator: true)
                                          .push(
                                        MaterialPageRoute(
                                          builder: (context) =>
                                              DetailCourseScreen(
                                            isPromo: true,
                                            idcourse: othersCourse.idCourse,
                                          ),
                                        ),
                                      );
                                    } else {
                                      Navigator.of(context, rootNavigator: true)
                                          .push(
                                        MaterialPageRoute(
                                          builder: (context) =>
                                              DetailCourseScreen(
                                            // isPromo: true,
                                            idcourse: othersCourse.idCourse,
                                          ),
                                        ),
                                      );
                                    }
                                  },
                                ),
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  );
                } else if (state.state == ResultState.noData ||
                    state.state == ResultState.error) {
                  return SearchNotFound();
                } else {
                  return Center(child: Text(''));
                }
              },
            ),
    );
  }
}
