
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:top_news_app/helper/image_cached.dart';
import 'package:top_news_app/model/Ads.dart';
import 'package:url_launcher/url_launcher.dart';

class AdsCardWidget extends StatefulWidget {
  final List<AdsData> ads;
  final AdsData data;
  const AdsCardWidget({super.key, required this.data, required this.ads});

  @override
  State<AdsCardWidget> createState() => _AdsCardWidgetState();
}

class _AdsCardWidgetState extends State<AdsCardWidget> {
  late int index = 0;
  bool isLoading = false;
  Future<void> _launchInBrowserView(Uri url) async {
    if (!await launchUrl(url, mode: LaunchMode.inAppBrowserView)) {
      throw Exception('Could not launch $url');
    }
  }

  AdsData adsData = AdsData();

  getTheIndex(){
    setState(() {
      isLoading = true;
    });


    if(widget.ads.isEmpty){
      adsData = widget.data;
    }else{
      Random random = Random();
      index = random.nextInt(widget.ads.length);
      adsData = widget.ads[index];
    }
    setState(() {
      isLoading = false;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getTheIndex();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return GestureDetector(
      onTap: (){
        _launchInBrowserView(Uri.parse('${adsData.url}'));
      },
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: SizedBox(
          height: 250,
          width: size.width,
          child: ImageCached(image: adsData.banner,
              width: size.width, blur: false, fit: BoxFit.cover,
              height: 250),
        ),
      ),
    );
  }
}
