import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:initial_folder/helper/validator.dart';
import 'package:initial_folder/providers/categories_provider.dart';
import 'package:initial_folder/providers/theme_provider.dart';
import 'package:initial_folder/screens/home/components/body_comp/course_by_category.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/custom_navigator.dart';
import 'package:initial_folder/widgets/login_regist/custom_font_awesome.dart';
import 'package:initial_folder/widgets/search_and_filter_course.dart';
import 'package:provider/provider.dart';
import 'component/list_category_icon.dart';
import 'package:shimmer/shimmer.dart';
import 'package:initial_folder/providers/search_provider.dart' as searchProv;
import 'package:initial_folder/providers/filters_course_provider.dart'
    as filterProv;

class SearchPage extends StatefulWidget {
  SearchPage({Key? key}) : super(key: key);

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final GlobalKey<NavigatorState> searchKey = GlobalKey<NavigatorState>();
  bool _showShimmer = false;

  @override
  Widget build(BuildContext context) {
     final themeProvider = Provider.of<ThemeProvider>(context);
    CategoriesProvider categoriesProvider =
        Provider.of<CategoriesProvider>(context);

    return WillPopScope(
      onWillPop: () async {
        if (searchKey.currentState!.canPop()) {
          searchKey.currentState!.pop();
          return false;
        }
        return true;
      },
      child: Navigator(
        key: searchKey,
        onGenerateRoute: (RouteSettings settings) {
          return MaterialPageRoute(
            builder: (BuildContext context) {
              if (settings.name == '/courseByCategory') {
                return CourseByCategory(
                  name: categoriesProvider.nameCategories[0] ?? '',
                  categoryId: categoriesProvider.ids[0] ?? '',
                  subId: '',
                );
              }
              return SafeArea(
                child: Scaffold(
                  backgroundColor:
                      Theme.of(context).brightness == Brightness.dark
                          ? twelveColor
                          : baruTextutih,
                  body: RefreshIndicator(
                    onRefresh: () async {
                      await categoriesProvider.getAllCategories();
                    },
                    child: SingleChildScrollView(
                      physics: AlwaysScrollableScrollPhysics(),
                      child: Container(
                        margin: EdgeInsets.symmetric(vertical: 10),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Expanded(
                                  child: Padding(
                                    padding: EdgeInsets.only(
                                      left: getProportionateScreenWidth(16),
                                      right: getProportionateScreenWidth(16),
                                    ),
                                    child: GestureDetector(
                                      onTap: () {
                                        Provider.of<searchProv.SearchProvider>(
                                                context,
                                                listen: false)
                                            .resetState();
                                        Provider.of<
                                                    filterProv
                                                    .FilterCourseProvider>(
                                                context,
                                                listen: false)
                                            .resetState();
                                        Provider.of<
                                                    filterProv
                                                    .FilterCourseProvider>(
                                                context,
                                                listen: false)
                                            .resetFilter();
                                        Navigator.push(
                                          context,
                                          CustomNavigator(
                                            child: SearchAndFilterCourse(),
                                          ),
                                        );
                                      },
                                      child: Container(
                                        decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(10),
                                          color: Theme.of(context).brightness ==
                                                  Brightness.dark
                                              ? seventeenColor
                                              : secondaryColor.withOpacity(0.3),
                                        ),
                                        height: 40,
                                        child: Row(
                                          children: [
                                            Padding(
                                              padding: const EdgeInsets.only(
                                                  left: 13),
                                              child: Icon(
                                                FeatherIcons.search,
                                                size: 20,
                                                color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode,
                                              ),
                                            ),
                                            SizedBox(
                                                width:
                                                    getProportionateScreenWidth(
                                                        10)),
                                            Text(
                                              'Cari kursus..',
                                              style:
                                                  secondaryTextStyle.copyWith(
                                                fontSize: 12,
                                                color: Theme.of(context)
                                                            .brightness ==
                                                        Brightness.dark
                                                    ? baruTextutih
                                                        .withOpacity(0.5)
                                                    : Colors.black
                                                        .withOpacity(0.5),
                                              ),
                                            )
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(height: getProportionateScreenWidth(16)),
                            Container(
                              margin: EdgeInsets.only(
                                  left: getProportionateScreenWidth(16)),
                              child: Text(
                                'Cari Berdasarkan Kategori',
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(16),
                                ),
                              ),
                            ),
                            SizedBox(height: getProportionateScreenWidth(12)),
                            Container(
                              child: Consumer<CategoriesProvider>(
                                  builder: (context, state, _) {
                                if (state.state == ResultState.Loading) {
                                  return Shimmer.fromColors(
                                    baseColor: Colors.white,
                                    highlightColor: Colors.grey,
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: List.generate(
                                        9,
                                        (index) => Padding(
                                          padding: const EdgeInsets.symmetric(
                                              vertical: 8.0, horizontal: 25.0),
                                          child: Row(
                                            children: [
                                              Container(
                                                width: 23,
                                                height: 23,
                                                decoration: BoxDecoration(
                                                  color: Colors.white,
                                                  borderRadius:
                                                      BorderRadius.circular(20),
                                                ),
                                              ),
                                              SizedBox(width: 15),
                                              Expanded(
                                                child: Container(
                                                  height: 10,
                                                  decoration: BoxDecoration(
                                                    color: Colors.white,
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            5),
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                  );
                                } else if (state.state == ResultState.HasData) {
                                  var categori = state.result;

                                  return Column(
                                    children: categori
                                        .map(
                                          (e) => ListCategoryIcon(
                                            title: e.nameCategory ?? '',
                                            iconFa: Icon(
                                              fontAwesomeIconsFromString(
                                                  'FontAwesomeIcons.${iconCategory(e.fontAwesomeClass ?? '')}'),
                                              size: getProportionateScreenWidth(
                                                  20),
                                            ),
                                            onTap: () {
                                              Navigator.push(
                                                context,
                                                CustomNavigator(
                                                  child: CourseByCategory(
                                                    name: e.nameCategory ?? '',
                                                    categoryId: e.id ?? '',
                                                    subId: '',
                                                  ),
                                                ),
                                              );
                                            },
                                          ),
                                        )
                                        .toList(),
                                  );
                                } else if (state.state == ResultState.NoData) {
                                  return Center(child: Text(state.message));
                                } else if (state.state == ResultState.Error) {
                                  if (!_showShimmer) {
                                    Future.delayed(Duration(seconds: 5), () {
                                      if (mounted) {
                                        setState(() {
                                          _showShimmer = true;
                                        });
                                      }
                                    });
                                    return Shimmer.fromColors(
                                      baseColor: Colors.white,
                                      highlightColor: Colors.grey,
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        children: List.generate(
                                          9,
                                          (index) => Padding(
                                            padding: const EdgeInsets.symmetric(
                                                vertical: 8.0,
                                                horizontal: 25.0),
                                            child: Row(
                                              children: [
                                                Container(
                                                  width: 23,
                                                  height: 23,
                                                  decoration: BoxDecoration(
                                                    color: Colors.white,
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            20),
                                                  ),
                                                ),
                                                SizedBox(width: 15),
                                                Expanded(
                                                  child: Container(
                                                    height: 10,
                                                    decoration: BoxDecoration(
                                                      color: Colors.white,
                                                      borderRadius:
                                                          BorderRadius.circular(
                                                              5),
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                    );
                                  } else {
                                    return Center(
                                      child: Padding(
                                        padding: EdgeInsets.only(
                                            top: getProportionateScreenHeight(
                                                70)),
                                        child: Text(
                                          "Internet lemah, mohon muat ulang",
                                        ),
                                      ),
                                    );
                                  }
                                } else {
                                  return Center(
                                    child: Text(
                                      'Terjadi Kesalahan ',
                                      style: primaryTextStyle,
                                    ),
                                  );
                                }
                              }),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

class Ic {
  String name;
  String tile;
  Ic({required this.name, this.tile = 'MaterialIcons'});
}
