import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:product_selector/common/widgets/appbar/appbar.dart';
import 'package:product_selector/common/widgets/custom_scaffold.dart';
import 'package:product_selector/screens/handsets/common/widget/search/model/search_argument.dart';
import 'package:product_selector/screens/handsets/handset_details/view/widgets/product_section.dart';
import 'package:product_selector/utilities/colors.dart';
import 'package:product_selector/utilities/utils.dart';
import 'package:video_player/video_player.dart';
import '../model/handset_details_model.dart' as aPrefix;
import '../view_model/handset_details_viewmodel.dart';

class HandsetDetails extends ConsumerStatefulWidget {
  static const routeName = '/handsetDetails';

  const HandsetDetails({Key? key}) : super(key: key);

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _HandsetDetailsState();
}

class _HandsetDetailsState extends ConsumerState<HandsetDetails> {
  late VideoPlayerController _controller;
  late Future<void> _initializeVideoPlayerFuture;
  bool isVideoInitialize = false;
  String url = '';
  String type = '';
  bool primary = true;
  HandsetDetailsViewState? handsetDetailsViewState;

  @override
  void initState() {
    _controller = VideoPlayerController.network('');
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final SearchArguments content =
          ModalRoute.of(context)!.settings.arguments as SearchArguments;

      ref
          .read(handsetDetailsViewModelProvider.notifier)
          .getHandsetDetailsServices(content.name!);
    });
  }

  @override
  void dispose() {
    // Ensure disposing of the VideoPlayerController to free up resources.
    if (isVideoInitialize) {
      _controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final handsetDetails = ref.watch(handsetDetailsViewModelProvider);
    final SearchArguments content =
        ModalRoute.of(context)!.settings.arguments as SearchArguments;
    return CustomScaffold(
      instance: this,
      isLoading: handsetDetails.isLoading,
      padding: EdgeInsetsDirectional.only(start: 52.w, end: 54.w, top: 51.h),
      appBarOptions: CustomAppBarOptions(instance: this),
      body: handsetDetails.isHasDataProduct!
          ? [
              Container(
                color: UIColors.darkBlack,
                height: 930.h,
                width: 974.w,
                child: RefreshIndicator(
                  onRefresh: () async {
                    ref
                        .read(handsetDetailsViewModelProvider.notifier)
                        .getHandsetDetailsServices(content.name!);
                  },
                  child: ListView(children: <Widget>[
                    Container(
                      color: UIColors.darkBlack,
                      height: 930.h,
                      width: 974.w,
                      child: handsetDetails
                                  .handsetDetailsResponse.primaryAsset!.url !=
                              null
                          ? videoTest(handsetDetails
                              .handsetDetailsResponse.primaryAsset!)
                          : const SizedBox(),
                    ),
                  ]),
                ),
              ),
              SizedBox(
                height: 20.h,
              ),
              listOfImages(handsetDetails.handsetDetailsResponse.assets ?? []),
              ProductSection(
                handsetDetailsModel: handsetDetails.handsetDetailsResponse,
                isHasAvailability:
                    handsetDetails.handsetDetailsResponse.isAvailable,
              ),
            ]
          : [
              Container(
                color: Colors.transparent,
                height: 930.h,
                width: 974.w,
                child: RefreshIndicator(
                  onRefresh: () async {
                    ref
                        .read(handsetDetailsViewModelProvider.notifier)
                        .getHandsetDetailsServices(content.name!);
                  },
                  child: ListView(children: <Widget>[
                    Container(
                      height: 930.h,
                      width: 974.w,
                    )
                  ]),
                ),
              ),
            ],
    );
  }

  Widget videoTest(aPrefix.Assets primaryAsset) {
    if (primaryAsset.type!.toLowerCase() == "video" && primary) {
      setState(() {
        isVideoInitialize = true;
        type = 'video';
        url = primaryAsset.url!;
        primary = true;
        // mutes the video
        _controller.setVolume(0);
        // Plays the video once the widget is build and loaded.
        _controller.play();
      });
      _controller = VideoPlayerController.network(getImgURL(primaryAsset.url));
      _initializeVideoPlayerFuture = _controller.initialize();
    }
    if (primaryAsset.type!.toLowerCase() == 'image' && primary) {
      setState(() {
        type = primaryAsset.type!.toLowerCase();
        url = primaryAsset.url!;
        primary = true;
      });
    }
    return type == 'video'
        ? FutureBuilder(
            future: _initializeVideoPlayerFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                return AspectRatio(
                  aspectRatio: _controller.value.aspectRatio,
                  child: VideoPlayer(_controller),
                );
              } else {
                return const Center(
                  child: CircularProgressIndicator(),
                );
              }
            },
          )
        : imageCard(url);
  }

  Widget listOfImages(List<aPrefix.Assets> images) {
    return SizedBox(
      height: 80.h,
      child: ListView.builder(
        //  itemExtent: screenSize(context).width / 11,
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemCount: images.length,
        itemBuilder: ((context, index) {
          return GestureDetector(
              onTap: () {
                setState(() {
                  type = images[index].type!.toLowerCase();
                  url = images[index].url!;
                  primary = false;
                  if (type == 'video') {
                    // Plays the video once the widget is build and loaded.
                    _controller = VideoPlayerController.network(getImgURL(url));
                    _initializeVideoPlayerFuture = _controller.initialize();
                    _controller.setVolume(0);
                    _controller.play();
                  }
                });
              },
              child: images[index].type!.toLowerCase() == 'image'
                  ? imageCard(images[index].url)
                  : Container(
                      width: 70.w,
                      height: 80.h,
                      decoration: const BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('assets/images/video.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                    ));
        }),
      ),
    );
  }

  Widget imageCard(image) {
    return Container(
        width: 70.w,
        height: 80.h,
        child:
            CachedNetworkImage(imageUrl: getImgURL(image), fit: BoxFit.fill));
  }
}
i want to swipe photos in videoTest widget left and right depend on assets returned in listOfImages widget