import 'package:aitrainer_app/bloc/menu/menu_bloc.dart';
import 'package:aitrainer_app/bloc/settings/settings_bloc.dart';
import 'package:aitrainer_app/bloc/tutorial/tutorial_bloc.dart';
import 'package:aitrainer_app/library/custom_icon_icons.dart';
import 'package:aitrainer_app/util/app_language.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/util/common.dart';
import 'package:aitrainer_app/util/enums.dart';
import 'package:aitrainer_app/util/track.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar_min.dart';
import 'package:aitrainer_app/widgets/bottom_nav.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:toggle_switch/toggle_switch.dart';
import 'package:url_launcher/url_launcher.dart';

// ignore: must_be_immutable
class SettingsPage extends StatelessWidget with Trans {
  @override
  Widget build(BuildContext context) {
    // ignore: close_sinks
    SettingsBloc settingsBloc = BlocProvider.of<SettingsBloc>(context);
    settingsBloc.setLocale(AppLanguage().appLocal);
    settingsBloc.context = context;
    setContext(context);

    MenuBloc menuBloc = BlocProvider.of<MenuBloc>(context);
    return Scaffold(
        appBar: AppBarMin(),
        body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('asset/image/WT_light_background.jpg'),
              fit: BoxFit.cover,
              alignment: Alignment.center,
            ),
          ),
          child: Form(
            child: BlocConsumer<SettingsBloc, SettingsState>(listener: (context, state) {
              if (state is SettingsError) {
                ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white))));
              } else if (state is SettingsReady) {
                menuBloc.add(MenuRecreateTree());
                Navigator.of(context).pushNamed("home");
              }
            }, builder: (context, state) {
              return ModalProgressHUD(
                child: settingsUI(context, settingsBloc, menuBloc),
                inAsyncCall: state is SettingsLoading,
                opacity: 0.5,
                color: Colors.black54,
                progressIndicator: CircularProgressIndicator(),
              );
            }),
          ),
        ),
        bottomNavigationBar: BottomNavigator(bottomNavIndex: 4));
  }

  ListView settingsUI(BuildContext context, SettingsBloc settingsBloc, MenuBloc menuBloc) {
    return ListView(padding: EdgeInsets.only(top: 150), children: <Widget>[
      ListTile(
          leading: Icon(Icons.language),
          subtitle: Text(t("Change App Language")),
          title: DropdownButton(
              value: settingsBloc.getLocale() == Locale('en') ? t("English") : t("Hungarian"),
              items: [t("English"), t("Hungarian")].map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
              onChanged: (lang) => {
                    settingsBloc.add(SettingsChangeLanguage(language: lang as String)),
                    Track().track(TrackingEvent.settings_lang, eventValue: lang)
                  })),
      getServer(settingsBloc),
      getTuturialBasic(settingsBloc),
      getTermsOfUse(),
      getPrivacy(),
      getFaq(),
      getVersion(),
      //getDevice(settingsBloc),
    ]);
  }

  ListTile getServer(SettingsBloc settingsBloc) {
    if (Cache().userLoggedIn == null || Cache().userLoggedIn!.admin != 1) {
      return ListTile(
        title: Container(),
      );
    }
    print("Live: ${Cache().liveServer}");
    return ListTile(
      leading: Icon(Icons.data_usage_sharp),
      subtitle: Text("For Test purpuses select Test-Server. After that please restart the the App"),
      title: ToggleSwitch(
        minWidth: 120.0,
        minHeight: 30.0,
        fontSize: 14.0,
        initialLabelIndex: Cache().liveServer
            ? Cache().testEnvironment == "1"
                ? 1
                : 0
            : 1,
        activeBgColor: Colors.indigo,
        activeFgColor: Colors.white,
        inactiveBgColor: Colors.white60,
        inactiveFgColor: Colors.grey[900],
        labels: [t('Live-Server'), t('Test-Server')],
        onToggle: (index) {
          settingsBloc.add(SettingsSetServer(live: index == 0));
        },
      ),
    );
  }

  ListTile getDevice(SettingsBloc settingsBloc) {
    return ListTile(
      leading: Common.badgedIcon(Colors.grey, CustomIcon.cog, "hardware"),
      subtitle: Text("Do you have Smart watch, or any device which collects the fit/health data?"),
      title: ToggleSwitch(
        minWidth: 120.0,
        minHeight: 30.0,
        fontSize: 14.0,
        initialLabelIndex: Cache().hasHardware! ? 0 : 1,
        activeBgColor: Colors.indigo,
        activeFgColor: Colors.white,
        inactiveBgColor: Colors.white60,
        inactiveFgColor: Colors.grey[900],
        labels: [t('Yes'), t('No')],
        onToggle: (index) {
          settingsBloc.add(SettingsSetHardware(hasHardware: index == 0));
        },
      ),
    );
  }

  ListTile getTuturialBasic(SettingsBloc settingsBloc) {
    final TutorialBloc tutorialBloc = BlocProvider.of<TutorialBloc>(context);
    return ListTile(
      leading: Icon(Icons.not_started),
      subtitle: Text(t("Activating the basic tutorial")),
      title: ToggleSwitch(
        minWidth: 120.0,
        minHeight: 30.0,
        fontSize: 14.0,
        initialLabelIndex: 0,
        activeBgColor: Colors.indigo,
        activeFgColor: Colors.white,
        inactiveBgColor: Colors.white60,
        inactiveFgColor: Colors.grey[900],
        labels: [t('Basic Tutorial'), t('Activate')],
        onToggle: (index) {
          ActivityDone activity = ActivityDone.tutorialBasic;
          if (Cache().userLoggedIn != null) {
            if (Cache().userLoggedIn!.sex == "m") {
              activity = ActivityDone.tutorialBasicChestPress;
            } else {
              activity = ActivityDone.tutorialBasicLegPress;
            }
          }
          settingsBloc.add(SettingsActivateTutorial(activity: activity));
          tutorialBloc.add(TutorialStart());
          Track().track(TrackingEvent.tutorial_activate);
        },
      ),
    );
  }

  ListTile getTermsOfUse() {
    return ListTile(
      leading: Icon(CustomIcon.user_cog),
      title: TextButton(
        child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Text("Terms Of Use", style: TextStyle(color: Colors.black)),
          Icon(
            Icons.arrow_forward_ios,
            color: Colors.indigo,
          ),
        ]),
        style: TextButton.styleFrom(
          backgroundColor: Colors.white70,
          onSurface: Colors.grey,
        ),
        onPressed: () => {
          Track().track(TrackingEvent.terms_of_use),
          _launchInBrowser("https://workouttest.com/terms-of-use/"),
        },
      ),
    );
  }

  ListTile getPrivacy() {
    return ListTile(
      leading: Icon(Icons.enhanced_encryption),
      title: TextButton(
        child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Text("Data Privacy", style: TextStyle(color: Colors.black)),
          Icon(
            Icons.arrow_forward_ios,
            color: Colors.indigo,
          ),
        ]),
        style: TextButton.styleFrom(
          backgroundColor: Colors.white70,
          onSurface: Colors.grey,
        ),
        onPressed: () => {
          Track().track(TrackingEvent.data_privacy),
          _launchInBrowser("https://workouttest.com/privacy/"),
        },
      ),
    );
  }

  ListTile getFaq() {
    return ListTile(
      leading: Icon(CustomIcon.question),
      title: TextButton(
        child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Text("Frequently Asked Questions", style: TextStyle(color: Colors.indigo)),
          Icon(
            Icons.arrow_forward_ios,
            color: Colors.indigo,
          ),
        ]),
        style: TextButton.styleFrom(
          backgroundColor: Colors.white70,
          onSurface: Colors.grey,
        ),
        onPressed: () => {
          Navigator.of(context).pushNamed("faqPage"),
          Track().track(TrackingEvent.faq),
        },
      ),
    );
  }

  Future<void> _launchInBrowser(String url) async {
    if (await canLaunch(url)) {
      await launch(
        url,
        forceSafariVC: false,
        forceWebView: false,
      );
    } else {
      throw 'Could not launch $url';
    }
  }

  ListTile getVersion() {
    final String version = Cache().packageInfo != null ? Cache().packageInfo!.version + "+" + Cache().packageInfo!.buildNumber : "";
    return ListTile(
      title: Text(
        "Version: $version",
        style: GoogleFonts.inter(fontSize: 12),
      ),
    );
  }
}
