import 'package:flutter/material.dart';
import 'package:flutter/src/gestures/tap.dart';
import 'package:guru_widgets/appbar/guru_app_bar.dart';
import 'package:guru_widgets/pages/settings/guru_settings_page.dart';
import 'package:guru_popup/guru_popup.dart';
import 'package:guru_app/ads/ads_manager.dart';
import 'package:guru_app/guru_app.dart';
import 'package:flutter/services.dart';
import 'package:guru_applovin_flutter/guru_applovin_flutter.dart';
import 'package:get/get.dart';
import 'package:guru_utils/extensions/extensions.dart';
import 'package:guru_utils/property/property.dart';
import 'package:guru_widgets/theme/guru_theme.dart';
import 'package:guru_utils/core/ext.dart';
import 'package:guru_utils/router/router.dart';
import 'package:guru_utils/property/property_model.dart';

import '../core/model.dart';
import '../data/setting.dart';
import '../core/property_keys.dart';
import '../dialog/editor/editor_dialog.dart';

class AdsDebugPage extends StatefulWidget {
  final LeadingType leadingType;
  final VoidCallback? initialCallback;
  final VoidCallback? onEnterAdsTest;

  const AdsDebugPage(
      {Key? key,
      this.leadingType = LeadingType.close,
      this.initialCallback,
      this.onEnterAdsTest})
      : super(key: key);
  
  @override
  State<StatefulWidget> createState() => AdsDebugState();
}


class AdsDebugState extends State<AdsDebugPage>{
  final profile = AdsManager.instance.adsProfile;
  static const gdprType = [GdprPopupType.admob, GdprPopupType.guru];
  static final List<String> geographyName = ["DISABLED", "EEA", "NOT_EEA", "DEFAULT"];

  bool forceGdpr = false;
  int forceGdprType = 0;
  DateTime latestShownFundingChoicesTime = DateTime(0);
  int consentDebugGeography = ConsentDebugGeography.names.length - 1;

  void resetGdpr() {
    AppProperty.getInstance().removeAllWithTag(UtilsPropertyTags.consent);
    AdsManager.instance.resetGdpr();
    setState(() {
      consentDebugGeography = ConsentDebugGeography.names.length - 1;
    });
    AppProperty.getInstance().remove(UtilsPropertyKeys.forceGdprType);
  }


  void resetPubmatic() {
    AppProperty.getInstance().remove(UtilsPropertyKeys.forcePubmatic);
    // forcePubmaticSubject.add(AdsManager.instance.adsConfig.bannerConfig.pubmaticEnable);
  }

  void setForceGdprType(int index) {
    AppProperty.getInstance().setString(UtilsPropertyKeys.forceGdprType, gdprType[index]);
    setState(() {
      forceGdprType = index;
    });
  }

  void setLatestShownFundingChoicesTimestamp(DateTime date) {
    AppProperty.getInstance().setInt(UtilsPropertyKeys.latestShownFundingChoicesTime, date.millisecondsSinceEpoch);
    setState(() {
      latestShownFundingChoicesTime = date;
    });
  }

  void _init() async {
    final forceGdprBol = await AppProperty.getInstance().getBool(UtilsPropertyKeys.forceGdpr, defValue: false);
    final consentDebugGeographyInt = await AppProperty.getInstance().getInt(UtilsPropertyKeys.consentDebugGeography, defValue: ConsentDebugGeography.names.length - 1);
    final forceGdprTypeIdx = gdprType.indexOf(GdprPopupType.admob);
    final ts = await AppProperty.getInstance().getInt(UtilsPropertyKeys.latestShownFundingChoicesTime, defValue: 0);
    
    setState(() {
      forceGdpr = forceGdprBol;
      consentDebugGeography = consentDebugGeographyInt;
      forceGdprType = forceGdprTypeIdx == -1 || forceGdprTypeIdx >= gdprType.length ? 0 : forceGdprTypeIdx;
      latestShownFundingChoicesTime = DateTime.fromMillisecondsSinceEpoch(ts);
    });
  }

  @override
  void initState() {
    super.initState();
    _init();
    widget.initialCallback?.call();
  }

  SettingItem _buildGdprGroup() {
    if (forceGdprType == 0) {
      return GroupSetting(
        title: "AdMob GDPR",
        items: [
          EntranceSetting(title: "Admob Consent Debug Geography", onTap: () async {
            await GuruPopup.instance.showCustomDialog(child: RadioGroupWidget(consentDebugGeography, geographyName.map((t) => Text(
                  t,
                  style: const TextStyle(fontSize: 16, color: Colors.black),
                ))
            .toList(), onChanged: (idx) {
              setForceGdprType(idx);
            }));
          }), 
          EntranceSetting(title: "Admob Consent Test Device Id", onTap: () async {
            final testDeviceId = await AppProperty.getInstance().getStringOrNull(UtilsPropertyKeys.admobConsentTestDeviceId);
            await GuruPopup.instance.showCustomDialog(child: EditorDialog(
            title: "Consent Test Device Id",
            hint: testDeviceId,
            onPositive: (text) async {
              if (DartExt.isNotBlank(text)) {
                await AppProperty.getInstance().setString(UtilsPropertyKeys.admobConsentTestDeviceId, text);
                GuruPopup.instance.showCommonToast("Set consent test device id success! ($text)");
              }
              RouteCenter.instance.back();
            },
            onNegative: (_) async {
              await AppProperty.getInstance().remove(UtilsPropertyKeys.admobConsentTestDeviceId);
              GuruPopup.instance.showCommonToast("clear consent test device id success!");
              RouteCenter.instance.back();
            },
            tips: RichText(
              text: TextSpan(
                  style: const TextStyle(
                      fontSize: 9,
                      fontWeight: GuruTheme.fwRegular,
                      color: Colors.white,
                      fontStyle: FontStyle.italic),
                  children: [
                const TextSpan(
                  text: "ENTER ",
                ),
                TextSpan(
                  text: "`adb logcat -s UserMessagingPlatform`",
                  style: const TextStyle(color: Colors.orange, decoration: TextDecoration.underline),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Clipboard.setData(
                          const ClipboardData(text: "adb logcat -s UserMessagingPlatform"));
                      GuruPopup.instance.showCommonToast("command copied");
                    },
                ),
                const TextSpan(
                  text: " to fetch DeviceId!",
                ),
              ]))));
          }),
          EntranceSetting(
            title: "Modify Latest Shown Funding Choices Ts", 
            summary: latestShownFundingChoicesTime.isAfter(DateTime(2022, 6, 10))
              ? latestShownFundingChoicesTime.toIso8601String() : "Not Shown", 
            onTap: () async {
              final dt = latestShownFundingChoicesTime;
              final selectedDate = await showDatePicker(
                context: Get.context!,
                initialDate: dt?.isAfter(DateTime(2022, 6, 10)) == true
                    ? dt ?? DateTime.now()
                    : DateTime.now(),
                firstDate: DateTime(2022, 6, 10),
                lastDate: DateTime.now().add(const Duration(days: 365)));

              final selectedTime = await showTimePicker(
                context: Get.context!,
                initialTime:
                dt != null ? TimeOfDay(hour: dt.hour, minute: dt.minute) : TimeOfDay.now());

              final newDateTime = DateTime(selectedDate?.year ?? dt.year, selectedDate?.month ?? dt.month,
                  selectedDate?.day ?? dt.day, selectedTime?.hour ?? dt.hour, selectedTime?.minute ?? dt.minute);
              
              setLatestShownFundingChoicesTimestamp(newDateTime); 
          })
        ]
      );
    } else {
      return GroupSetting(
        title: "GURU GDPR",
        items: [
          SwitchSetting(
            enabledTitle: "Force Show Guru Gdpr",
            settingData: DebugModeSettings.instance.forceGdpr,
            onChanged: (value) {
              DebugModeSettings.instance.forceGdpr.set(value);
          }),
        ]
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return GuruSettingsPage(
      leadingType: LeadingType.back,
      subpage: true,
      items: [
        GroupSetting(
          title: "MAX SUPPORT",
          items: [
            EntranceSetting(title: "MAX Mediation Debugger", onTap: () async {
              GuruApplovinFlutter.instance.openDebugger();
            }), 
            EntranceSetting(title: "GURU Mediation Debugger", onTap: () {
              widget.onEnterAdsTest?.call();
            }),
            SwitchSetting(
              enabledTitle: "Fake Interstitial Ads",
              settingData: DebugModeSettings.instance.fakeInterstitialAds,
              onChanged: (value) {
                DebugModeSettings.instance.fakeInterstitialAds.set(value);
                RuntimeProperty.instance.setBool(UtilsPropertyKeys.fakeInterstitialAds, value);
            }),
            SwitchSetting(
              enabledTitle: "Fake Rewarded Ads",
              settingData: DebugModeSettings.instance.fakeRewardedAds,
              onChanged: (value) {
                DebugModeSettings.instance.fakeRewardedAds.set(value);
                RuntimeProperty.instance.setBool(UtilsPropertyKeys.fakeRewardedAds, value);
            }),
          ]
        ),
        GroupSetting(
          title: "GDPR",
          items: [
            EntranceSetting(title: "Reset Gdpr", onTap: () async {
              resetGdpr();
            }), 
            EntranceSetting(title: "GDPR TYPE", onTap: () async {
              await GuruPopup.instance.showCustomDialog(child: RadioGroupWidget(forceGdprType, gdprType.map((t) => Text(
                    t,
                    style: const TextStyle(fontSize: 16, color: Colors.black),
                  ))
              .toList(), onChanged: (i) {
                setForceGdprType(i);
              }));
            })
          ]
        ),
        _buildGdprGroup(),
        GroupSetting(
          title: "PUBMATIC",
          items: [
            SwitchSetting(
              enabledTitle: "Force Pubmatic",
              settingData: DebugModeSettings.instance.forcePubmatic,
              onChanged: (value) {
                DebugModeSettings.instance.forcePubmatic.set(value);
            }),
            EntranceSetting(title: "Reset Pubmatic", onTap: () async {
              resetPubmatic();
            })
          ]
        ),
        GroupSetting(
          title: "DATA",
          items: [
            EntranceSetting(title: "Ads Remote Config", onTap: () async {
              GuruPopup.instance.showKeyValueDialog(AdsManager.instance.adsConfig.dump().entries.toList());
            }),
            EntranceSetting(title: "Ads Properties", onTap: () async {

            })
          ]
        ),
        GroupSetting(
          title: "IDS",
          items: [
            EntranceSetting(title: "Banner AdUnitId", summary: profile.bannerId.id, onTap: () async {
              Clipboard.setData(ClipboardData(text: profile.bannerId.id));
              Log.d("saveTokenToClipboard:${profile.bannerId.id}");
              GuruPopup.instance.showCommonToast("Copied Banner AdUnitId to your clipboard");
            }),
            EntranceSetting(title: "Interstitial AdUnitId", summary: profile.interstitialId.id, onTap: () async {
              Clipboard.setData(ClipboardData(text: profile.interstitialId.id));
              Log.d("saveTokenToClipboard:${profile.interstitialId.id}");
              GuruPopup.instance.showCommonToast("Copied Interstitial AdUnitId to your clipboard");
            }),
            EntranceSetting(title: "Rewarded AdUnitId", summary: profile.rewardsId.id, onTap: () async {
              Clipboard.setData(ClipboardData(text: profile.rewardsId.id));
              Log.d("saveTokenToClipboard:${profile.rewardsId.id}");
              GuruPopup.instance.showCommonToast("Copied Rewarded AdUnitId to your clipboard");
            })
          ]
        )
      ]
    );
  }
}



class RadioGroupWidget extends StatefulWidget {
  final MainAxisAlignment mainAxisAlignment;
  final MainAxisSize mainAxisSize;
  final CrossAxisAlignment crossAxisAlignment;

  final TextDirection? textDirection;
  final Axis direction;

  final int initialIndex;
  final List<Widget> items;
  final void Function(int)? onChanged;

  RadioGroupWidget(this.initialIndex, this.items,
      {this.mainAxisAlignment = MainAxisAlignment.start,
      this.mainAxisSize = MainAxisSize.min,
      this.crossAxisAlignment = CrossAxisAlignment.start,
      this.direction = Axis.vertical,
      this.textDirection,
      this.onChanged});

  @override
  State<StatefulWidget> createState() {
    return RadioGroupState();
  }
}

class RadioGroupState extends State<RadioGroupWidget> {
  int groupValue = 0;

  final List<Widget> _items = [];

  void _refresh() {
    _items.clear();

    for (int index = 0; index < widget.items.length; ++index) {
      _items.add(Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Radio<int>(
            value: index,
            groupValue: groupValue,
            onChanged: (v) {
              setState(() {
                groupValue = v ?? 0;
              });
              widget.onChanged?.call(v ?? 0);
            },
          ),
          InkWell(
            onTap: () {
              setState(() {
                groupValue = index;
              });
              widget.onChanged?.call(index);
            },
            child: widget.items[index],
          )
        ],
      ));
    }
  }

  @override
  void initState() {
    super.initState();
    groupValue = widget.initialIndex;
  }

  @override
  void didUpdateWidget(covariant RadioGroupWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    _refresh();
    if (widget.direction == Axis.vertical) {
      return Column(
        mainAxisAlignment: widget.mainAxisAlignment,
        mainAxisSize: widget.mainAxisSize,
        crossAxisAlignment: widget.crossAxisAlignment,
        children: _items,
      );
    } else {
      return Row(
        mainAxisAlignment: widget.mainAxisAlignment,
        mainAxisSize: widget.mainAxisSize,
        crossAxisAlignment: widget.crossAxisAlignment,
        children: _items,
      );
    }
  }
}