import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import '../../../../../constants/constants.dart';
import '../../../../../core/utils/app_utils.dart';
import '../../../data/models/banner_response.dart';
import '../../mixin/banner_mixin.dart';

class BannersWidget extends StatefulWidget {
  const BannersWidget({super.key, required this.banners});

  final List<BannerResponse>? banners;

  @override
  State<BannersWidget> createState() => _BannersWidgetState();
}

class _BannersWidgetState extends State<BannersWidget> with BannerMixin {
  Timer? timer;

  @override
  void initState() {
    initController();
    if ((widget.banners?.length ?? 0) > 1) {
      animationTimer();
    }
    super.initState();
  }

  @override
  void didUpdateWidget(covariant BannersWidget oldWidget) {
    if ((widget.banners?.length ?? 0) > 1) {
      animationTimer();
    } else if ((widget.banners?.length ?? 0) == 1) {
      if (timer?.isActive ?? false) {
        timer?.cancel();
      }
    }
    super.didUpdateWidget(oldWidget);
  }

  void animationTimer() {
    if (timer?.isActive ?? false) {
      timer?.cancel();
    }
    timer = Timer.periodic(const Duration(seconds: 4), (Timer timer) async {
      pageController.nextPage(
        duration: const Duration(milliseconds: 800),
        curve: Curves.fastOutSlowIn,
      );
    });
  }

  @override
  void dispose() {
    timer?.cancel();
    pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Padding(
        padding: const EdgeInsets.only(bottom: 16),
        child: SizedBox(
          height: 180,
          width: double.infinity,
          child: PageView.builder(
            controller: pageController,
            itemCount: (widget.banners?.length ?? 0) > 1
                ? null
                : widget.banners?.length,
            scrollDirection: Axis.horizontal,
            physics: widget.banners?.length != 1
                ? null
                : const NeverScrollableScrollPhysics(),
            itemBuilder: (_, index) => GestureDetector(
              onTap: () {},
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 4),
                child: ClipRRect(
                  borderRadius: AppUtils.kBorderRadius16,

                  child: CachedNetworkImage(
                    imageUrl:
                        "${Constants.baseUrl}${widget.banners?[index % (widget.banners?.length ?? 1)].image}",
                    height: 180,
                    width: double.infinity,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
