import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:ongbut_ntmanh/app/module/course/model/list_data.dart';
import '../../const/colors.dart';
import '../../res/images/images.dart';
import '../module/course/bloc/course_bloc.dart';
import '../module/course/model/course_model.dart';
import '../module/coursedetail/widgets/course_detail.dart';

final scrollController = ScrollController();
class SearchWidget extends StatelessWidget {
  SearchWidget({Key? key}) : super(key: key);
  CourseModel? courseModel;
  List<ListData> listData = [];
  @override
  Widget build(BuildContext context) {
    BlocProvider.of<CourseBloc>(context).add(
        RequestCourse(context: context));
    return
      Scaffold(
        appBar: AppBar(title: Text('Tat ca cac khoa hoc'),),
        body:
        BlocBuilder<CourseBloc, CourseState>(
          builder: (context, state) {
            if(state is CourseInitial){
              const CircularProgressIndicator();
            }
            if(state is CourseLoading){
              return const CircularProgressIndicator();
            }
            if(state is CourseFailed){
              return Text(state.message.toString());
            }
            if(state is CourseSuccess){
              listData = state.courseModel.data!.listData!;
              return
                Container(
                  height: double.maxFinite,
                  width: double.maxFinite,
                  color: AppColors.background,
                  alignment: Alignment.topCenter,
                  child: CustomScrollView(
                    scrollDirection: Axis.vertical,// listview vuot ngang
                    slivers:<Widget>[
                      SliverGrid(
                        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                          maxCrossAxisExtent: 350,
                          mainAxisSpacing: 0,
                          crossAxisSpacing: 0,
                          childAspectRatio: 0.65,
                        ),
                        delegate: SliverChildBuilderDelegate(
                              (BuildContext context, int index) {
                            if (index < listData.length) {
                              return _courseList(listData[index], context);
                            } else {
                              Timer(const Duration(milliseconds: 20), () {
                                scrollController
                                    .jumpTo(scrollController.position.maxScrollExtent);
                              });
                              return const CircularProgressIndicator();
                            }
                          },
                          childCount: listData.length,
                        ),
                      ),
                    ],
                  ),
                );
            }
            return const Text('CourseFailed');
          }
      ),);

  }
}

Widget _courseList( listData, BuildContext context) {
  return InkWell(
    onTap: (){
      Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => CourseDetailWidget(listData.courseId!,listData.image!=null?listData.image!:'https://oss.myitsol.com/imes-public/2022/12/11/neymar_145527553.PNG'),
          )
      );
      // .then((value) {
      // if (value != null && value is bool && value) {}
      // });
    },
    child: Padding(
      padding: const EdgeInsets.fromLTRB(15, 15, 15, 15),
      child:
      Container(
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),
            color: AppColors.white),
        child: Column(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(8.0),
              child:
              Image.network(listData.image!=null?listData.image!:'https://oss.myitsol.com/imes-public/2022/12/11/neymar_145527553.PNG',
                fit: BoxFit.fill,
                errorBuilder: (BuildContext context, Object exception,
                    StackTrace? stackTrace) {
                  return Image.asset(Images.load_err);
                },
                height: 130,
                // height: checkLandscape(context)?getHeight(context)*0.25:getHeight(context)*0.15,
                width: double.maxFinite,
              ),
            ),
            Padding(
              padding: const EdgeInsets.fromLTRB(10, 10, 10,10),
              child: Container(
                alignment: Alignment.centerLeft,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                      child: Text(listData.name ?? 'Null',softWrap: false,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis),
                    ),
                    Text(listData.keyword ?? 'Null',softWrap: false,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 40, 0, 0),
                      child: OutlinedButton(
                        onPressed: () {  },
                        style: OutlinedButton.styleFrom(
                          minimumSize: const Size.fromHeight(35),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20.0),
                          ),
                          backgroundColor: Colors.white,// background
                          primary: AppColors.primary, // foreground text
                          side: const BorderSide(color: AppColors.primary), // foreground border
                        ),
                        child: const Text('Dang Ky', style: TextStyle(fontSize: 15)),
                      ),
                    ),
                  ],
                ),
              ),
            ),

          ],
        ),
      ),
    ),
  );
}
