import 'dart:io';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

class BannerAdContainer extends StatefulWidget {
  const BannerAdContainer({super.key});

  @override
  State<BannerAdContainer> createState() => _BannerAdContainerState();
}

class _BannerAdContainerState extends State<BannerAdContainer> {
  BannerAd? bannerAd;
  Container adContainer = Container();
  int retryAttempt = 0;
  @override
  void didChangeDependencies() {
    double width = MediaQuery.of(context).size.width;
    loadBannerAd(width);
    super.didChangeDependencies();
  }

  void loadBannerAd(double width) async {
    String adUnitId = '';
    AdSize adSize = AdSize.banner;
    if (width >= 468) adSize = AdSize.fullBanner;
    if (width >= 728) adSize = AdSize.leaderboard;
    if (!kReleaseMode) {
      if (Platform.isAndroid) {
        adUnitId = 'ca-app-pub-3940256099942544/6300978111'; //official android debug banner ad unit id
      } else if (Platform.isIOS) {
        adUnitId = 'ca-app-pub-3940256099942544/2934735716'; //official iOS debug banner ad unit id
      }
    } else {
      if (Platform.isAndroid) {
        adUnitId = 'ca-app-pub-6574362285928731/9669436762'; //TODO enter your own Android Ad Unit ID
      } else if (Platform.isIOS) {
        adUnitId = 'ca-app-pub-6574362285928731/7781640020'; //TODO enter your own iOS Ad Unit ID
      }
    }
    if (adUnitId.isNotEmpty) {
      bannerAd = BannerAd(
        adUnitId: adUnitId,
        size: adSize,
        request: const AdRequest(),
        listener: BannerAdListener(
          onAdLoaded: (ad) => print('ad loaded'),
          onAdFailedToLoad: (ad, error) {
            print('ad failed to load: $error');
            // Dispose the ad here to free resources.
            ad.dispose();
            retryAttempt = retryAttempt + 1;
            int retryDelay = pow(2, min(6, retryAttempt)).toInt();
            print("retryDelay $retryDelay");
            Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
              loadBannerAd(MediaQuery.of(context).size.width);
            });
          },
          onAdClicked: (ad) => print('ad clicked'),
          onAdOpened: (ad) => print('ad opened'),
          onAdClosed: (ad) => print('ad closed'),
        ),
      );
      await bannerAd?.load();
      if (bannerAd != null) {
        final AdWidget adWidget = AdWidget(ad: bannerAd!);
        print('ad width: ${bannerAd!.size.width}');
        print('ad height: ${bannerAd!.size.height}');
        adContainer = Container(
          alignment: Alignment.center,
          width: bannerAd!.size.width.toDouble(),
          height: bannerAd!.size.height.toDouble(),
          child: adWidget,
        );
        if (mounted) setState(() {});
      }
    }
  }

  void destroyBannerAd() {
    adContainer = Container();
    bannerAd?.dispose();
    bannerAd = null;
  }

  @override
  void dispose() {
    destroyBannerAd();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return adContainer;
  }
}