import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';

class DidvanSlider extends StatefulWidget {
  final Widget Function(BuildContext context, int index, int realIndex)
      itemBuilder;
  final int itemCount;
  final double viewportFraction;
  final bool? enableIndicator;
  final double? height;
  final void Function(int, CarouselPageChangedReason)? onPageChanged;
  const DidvanSlider({
    super.key,
    required this.itemBuilder,
    required this.itemCount,
    required this.viewportFraction,
    this.onPageChanged,
    this.enableIndicator,
    this.height,
  });

  @override
  State<DidvanSlider> createState() => _DidvanSliderState();
}

class _DidvanSliderState extends State<DidvanSlider> {
  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        CarouselSlider.builder(
          itemCount: widget.itemCount,
          itemBuilder: widget.itemBuilder,
          options: CarouselOptions(
            height: widget.height,
            autoPlay: true,
            padEnds: false,
            viewportFraction: widget.viewportFraction,
            onPageChanged: (index, reason) {
              widget.onPageChanged?.call(index, reason);
              if (widget.enableIndicator == true) {
                setState(() {
                  _currentIndex = index;
                });
              }
            },
          ),
        ),
        if (widget.enableIndicator == true) ...[
          const SizedBox(height: 8),
          _CarouselIndicator(
            count: widget.itemCount,
            currentIndex: _currentIndex,
          ),
        ],
      ],
    );
  }
}

class _CarouselIndicator extends StatelessWidget {
  final int count;
  final int currentIndex;
  const _CarouselIndicator({required this.count, required this.currentIndex});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        for (int i = 0; i < count; i++)
          Container(
            width: 7,
            height: 7,
            margin: const EdgeInsets.symmetric(horizontal: 2),
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              boxShadow: [
                BoxShadow(
                  color: currentIndex == i ? const Color.fromARGB(255, 176, 215, 228) : Colors.transparent,
                  blurRadius: 0,
                  spreadRadius: 2.5,
                  offset: const Offset(0, 0),
                ),
              ],
              color: currentIndex == i
                  ? const Color.fromARGB(255, 0, 126, 167)
                  : const Color.fromARGB(255, 173, 173, 173),
            ),
          )
      ],
    );
  }
}
