import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/src/intl/date_format.dart';
import 'package:guru_app/guru_app.dart';
import 'package:guru_app/firebase/messaging/remote_messaging_manager.dart';
import 'package:guru_analytics_flutter/guru/guru_statistic.dart';
import 'package:guru_app/analytics/guru_analytics.dart';
import 'package:guru_app/property/property_keys.dart';
import 'package:guru_app/account/account_data_store.dart';
import 'package:guru_app/firebase/remoteconfig/remote_config_manager.dart';
import 'package:guru_widgets/pages/settings/guru_settings_page.dart';
import 'package:guru_widgets/appbar/guru_app_bar.dart';
import 'package:guru_popup/guru_popup.dart';
import 'package:guru_utils/analytics/analytics.dart';
import 'package:guru_utils/property/runtime_property.dart';
import 'package:guru_utils/property/app_property.dart';
import 'package:guru_utils/extensions/extensions.dart';
import 'package:guru_utils/device/device_utils.dart';

import '../core/property_keys.dart';
import '../data/setting.dart';


class DataViewerPage extends StatefulWidget {
  final List<InseparableSettingItem>? items;
  final List<InseparableSettingItem>? firebaseItems;
  final List<InseparableSettingItem>? propertiesItems;
  final List<InseparableSettingItem>? commonItems;
  final List<InseparableSettingItem>? accountItems;

  const DataViewerPage(
      {Key? key,
      this.items,
      this.firebaseItems,
      this.propertiesItems,
      this.commonItems,
      this.accountItems})
      : super(key: key);
  
  @override
  State<StatefulWidget> createState() => DataViewerState();
}

class DataViewerState extends State<DataViewerPage>{
  DateTime firstInstallDate = DateTime(0);
  String? fcmToken = RemoteMessagingManager.instance.fcmToken.value;
  GuruStatistic? statistic = GuruAnalytics.instance.guruEventStatistic.value ?? GuruStatistic.invalid;

  void setFirstInstallDate(DateTime? date) {
    if (date != null) {
      final firstInstallTime = date.millisecondsSinceEpoch;
      AppProperty.getInstance().setInt(PropertyKeys.firstInstallTime, firstInstallTime);
      RuntimeProperty.instance.setInt(PropertyKeys.firstInstallTime, firstInstallTime);
      setState(() {
        firstInstallDate = date;
      });
    }
  }

  void _init() async {
    final firstInstallTime = await AppProperty.getInstance()
        .getOrCreateInt(PropertyKeys.firstInstallTime, DateTime.now().millisecondsSinceEpoch);
    setState(() {
      firstInstallDate = DateTime.fromMillisecondsSinceEpoch(firstInstallTime);
    });
  }

  @override
  void initState() {
    super.initState();
    _init();
  }

  @override
  Widget build(BuildContext context) {
    return GuruSettingsPage(
      leadingType: LeadingType.back,
      subpage: true,
      items: [
        GroupSetting(
          title: "FIREBASE",
          items: [
            EntranceSetting(title: "Push Token", summary: fcmToken ?? "", onTap: () async {
              Clipboard.setData(ClipboardData(text: fcmToken ?? ""));
              Log.d("saveTokenToClipboard:$fcmToken");
              GuruPopup.instance.showCommonToast("Copied FCMToken to your clipboard");
            }), 
            EntranceSetting(title: "Analytics Event Data", summary: "uploaded:${statistic?.uploaded} logged:${statistic?.logged} }", onTap: () {
              GuruAnalytics.instance.refreshEventStatistic(force: true);
              GuruPopup.instance.showKeyValueDialog(Analytics.latestEventRecords.toList());
            }),
            EntranceSetting(title: "Export Guru Analytics Log", onTap: () async {
              final path = await GuruAnalytics.instance.zipGuruLogs();
              final file = File(path);
              // ShareUtils.shareZipFile(file);
            }),
            EntranceSetting(title: "Remote Config", onTap: () {
              GuruPopup.instance.showKeyValueDialog(RemoteConfigManager.instance.allData().entries.toList());
            }),
            EntranceSetting(title: "User properties / Screen", onTap: () {
              GuruPopup.instance.showKeyValueDialog(Analytics.userProperties.entries.toList());
            }),
            ...?widget?.firebaseItems
          ]
        ),
        GroupSetting(
          title: "PROPERTIES",
          items: [
            EntranceSetting(title: "Runtime Properties", onTap: () async {
              GuruPopup.instance.showKeyValueDialog(RuntimeProperty.instance.toNamedMapEntries());
            }),
            EntranceSetting(title: "App Properties", onTap: () async {
              GuruPopup.instance.showKeyValueDialog(
              (await AppProperty.getInstance().loadAllValues()).toNamedMapEntries());
            }),
            ...?widget?.propertiesItems
          ]
        ),
        GroupSetting(
          title: "COMMON",
          items: [
            SwitchSetting(
              enabledTitle: "Global Floating Window",
              settingData: DebugModeSettings.instance.globalFloatingWindow,
              onChanged: (value) {
                DebugModeSettings.instance.fakeRewardedAds.set(value);
                RuntimeProperty.instance.setBool(DataViewerPropertyKeys.globalFloatingWindow, value);
            }),
            EntranceSetting(
              title: "Modify First Install Time", 
              summary: firstInstallDate.isAfter(DateTime(2022, 6, 10))
                      ? DateFormat.yMd().format(firstInstallDate)
                      : "Not Shown", 
              onTap: () async {
                final selectedDate = await showDatePicker(
                  context: context,
                  initialDate: firstInstallDate.isAfter(DateTime(2022, 6, 10)) == true
                      ? firstInstallDate ?? DateTime.now()
                      : DateTime.now(),
                  firstDate: DateTime(2022, 6, 10),
                  lastDate: DateTime.now().add(const Duration(days: 365)));
                setFirstInstallDate(selectedDate);
              }
            ),
            ...?widget?.commonItems
          ]
        ),
        GroupSetting(
          title: "ACCOUNT",
          items: [
            EntranceSetting(title: "Account Data Store", onTap: () async {
              final accountDataStore = AccountDataStore.instance;
              GuruPopup.instance.showKeyValueDialog(<String, String>{
                "nickname": accountDataStore.nickname ?? "",
                "uid": accountDataStore.uid ?? "",
                // "bestScore": accountDataStore.bestScore.displayNum ?? "",
                "countryCode":
                    "${DeviceUtils.countryCodeToFlagEmoji(accountDataStore.countryCode ?? "CN")}(${accountDataStore.countryCode})",
                "avatar": accountDataStore.avatar ?? "",
                "saasToken": accountDataStore.saasToken ?? "",
                "accountDataStatus": accountDataStore.accountDataStatus.toString(),
                "initRetryCount": accountDataStore.initRetryCount.toString()
              }.entries.toList());
            }),
            ...?widget?.accountItems
          ]
        ),
        ...?widget?.items
      ]
    );
  }
}