import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:initial_folder/models/banners_model.dart';
import 'package:initial_folder/providers/banners_provider.dart';
import 'package:initial_folder/screens/detail_course/detail_course_screen.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/custom_navigator.dart';
import 'package:initial_folder/widgets/terms_and_privacy.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';
import '../../../../size_config.dart';

class CarouselWithIndicatorDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _CarouselWithIndicatorState();
  }
}

class _CarouselWithIndicatorState extends State<CarouselWithIndicatorDemo> {
  int _current = 0;

  @override
  Widget build(BuildContext context) {
    Widget listBannerPicture(BannersModel listBanner) {
      return InkWell(
        onTap: () {
          String? idCourse;
          if (listBanner.courseId.isNotEmpty) {
            idCourse = listBanner.courseId;
          } else {
            if (listBanner.url!.isNotEmpty) {
              if (listBanner.url!
                  .contains('https://vocasia-v4-develop.vercel.app/')) {
                List<String> urlList = listBanner.url!.split('/');
                try {
                  idCourse = urlList.last;
                } on StateError {
                  idCourse = '0';
                }
                Navigator.of(context, rootNavigator: true).push(
                  CustomNavigator(
                    child: DetailCourseScreen(
                      idcourse: idCourse ?? '0',
                    ),
                  ),
                );
              } else {
                Navigator.of(context, rootNavigator: true).push(
                  MaterialPageRoute(
                    builder: (context) => TermsAndCondition(
                      // url: 'https://vocasia.id/home/contact',
                      url: listBanner.url!,
                    ),
                  ),
                );
              }
            }
          }
        },
        splashColor: Colors.white10,
        child: Container(
          margin: EdgeInsets.symmetric(
            horizontal: getProportionateScreenWidth(16),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(10)),
            child: AspectRatio(
              aspectRatio: 2,
              child: CachedNetworkImage(
                fadeInDuration: Duration(microseconds: 1),
                imageUrl: listBanner.img.toString(),
                fit: BoxFit.contain,
                placeholder: (context, url) => Shimmer(
                    child: Container(
                      decoration: BoxDecoration(
                        color: ninthColor,
                        borderRadius: BorderRadius.circular(5),
                      ),
                    ),
                    gradient: LinearGradient(
                        stops: [0.2, 0.5, 0.6],
                        colors: [ninthColor, fourthColor, ninthColor])),
                errorWidget: (context, url, error) => Icon(Icons.error),
              ),
            ),
          ),
        ),
      );
    }

    return Container(
      child: Consumer<BannersProvider>(builder: (context, state, _) {
        if (state.state == ResultState.Loading) {
          return Padding(
            padding: const EdgeInsets.all(18.0),
            child: Shimmer.fromColors(
                baseColor: Colors.white,
                highlightColor: Colors.grey,
                child: Container(
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      color: Colors.white),
                  height: 210,
                  width: 50,
                )),
          );
        } else if (state.state == ResultState.HasData) {
          return Container(
            child: Column(
              children: [
                CarouselSlider(
                  items: state.result
                      .map((banner) => listBannerPicture(banner))
                      .toList(),
                  options: CarouselOptions(
                      height: getProportionateScreenHeight(200),
                      disableCenter: true,
                      autoPlay: true,
                      autoPlayInterval: Duration(seconds: 10),
                      enlargeCenterPage: true,
                      viewportFraction: 1,
                      aspectRatio: 2,
                      onPageChanged: (index, reason) {
                        setState(() {
                          _current = index;
                        });
                      }),
                ),
                Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: state.result.map((url) {
                      int index = state.result.indexOf(url);
                      return Container(
                        width: getProportionateScreenWidth(6.0),
                        height: getProportionateScreenWidth(6.0),
                        margin: EdgeInsets.symmetric(
                            horizontal: getProportionateScreenWidth(3.0),
                            vertical: getProportionateScreenWidth(16)),
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: _current == index ? thirdColor : fourthColor,
                        ),
                      );
                    }).toList()),
              ],
            ),
          );
        } else if (state.state == ResultState.NoData) {
          final defaultBanners = [
            'assets/images/deffault_banner.png',
            'assets/images/default_banner_2.png'
          ];

          return Column(
            children: [
              CarouselSlider.builder(
                itemCount: defaultBanners.length,
                itemBuilder: (context, index, realIndex) {
                  return Image.asset(
                    defaultBanners[index],
                    width: double.infinity,
                  );
                },
                options: CarouselOptions(
                  height: getProportionateScreenHeight(200),
                  autoPlay: true,
                  autoPlayInterval: Duration(seconds: 10),
                  enlargeCenterPage: true,
                  viewportFraction: 1,
                  aspectRatio: 2,
                  onPageChanged: (index, reason) {
                    setState(() {
                      _current = index;
                    });
                  },
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: List.generate(defaultBanners.length, (index) {
                  return Container(
                    width: getProportionateScreenWidth(6.0),
                    height: getProportionateScreenWidth(6.0),
                    margin: EdgeInsets.symmetric(
                      horizontal: getProportionateScreenWidth(3.0),
                      vertical: getProportionateScreenWidth(16),
                    ),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: _current == index ? thirdColor : fourthColor,
                    ),
                  );
                }),
              ),
            ],
          );
        } else if (state.state == ResultState.Error) {
          return Padding(
            padding: EdgeInsets.only(
              left: getProportionateScreenWidth(76),
              top: getProportionateScreenHeight(45),
            ),
            child: Container(
              width: getProportionateScreenWidth(480),
              height: getProportionateScreenHeight(100),
              color: Colors.transparent,
              child: Text('Internet lemah, mohon muat ulang'),
            ),
          );
        } else {
          return Center(child: Text(''));
        }
      }),
    );
  }
}
