import 'package:anyway/constants.dart';
import 'package:anyway/main.dart';
import 'package:anyway/pages/base_page.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';


bool debugMode = false;

class SettingsPage extends StatefulWidget {
  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  @override
  Widget build(BuildContext context) {
    return BasePage(
      mainScreen: ListView(
        padding: EdgeInsets.all(15),
        children: [
          // First a round, centered image
          Center(
            child: CircleAvatar(
              radius: 75,
              child: Icon(Icons.settings, size: 100),
            )
          ),
          Center(
            child: Text('Global settings', style: TextStyle(fontSize: 24))
          ),

          Divider(indent: 25, endIndent: 25, height: 50),

          darkMode(),
          setLocationUsage(),
          setDebugMode(),

          Divider(indent: 25, endIndent: 25, height: 50),

          privacyInfo(),
        ]
      ),
      title: Text('Settings'),
      helpTexts: [
        'Settings',
        'Preferences set in this page are global and will affect the entire application.'
      ],
    );
  }

  Widget setDebugMode() {
    return Row(
      children: [
        Text('Debugging: use a custom API URL'),
        // white space
        Spacer(),
        Switch(
          value: debugMode,
          onChanged: (bool? newValue) {
            setState(() {
              debugMode = newValue!;
              if (debugMode) {
                showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return AlertDialog(
                      title: Text('Debug mode - use a custom API endpoint'),
                      content: TextField(
                        controller: TextEditingController(text: API_URL_DEBUG),
                        onChanged: (value) {
                          setState(() {
                            API_URL_BASE = value;
                          });
                        },
                      ),
                      actions: [
                        TextButton(
                          child: Text('OK'),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                      ],
                    );
                  }
                );
              }
            });
          }
        )
      ],
    );
  }

  Widget darkMode() {
    return Row(
      children: [
        Text('Dark mode'),
        Spacer(),
        Switch(
          value: Theme.of(context).brightness == Brightness.dark,
          onChanged: (bool? newValue) {
            setState(() {
              rootScaffoldMessengerKey.currentState!.showSnackBar(
                SnackBar(content: Text('Dark mode is not implemented yet'))
              );
              // if (newValue!) {
              //   // Dark mode
              //   Theme.of(context).brightness = Brightness.dark;
              // } else {
              //   // Light mode
              //   Theme.of(context).brightness = Brightness.light;
              // }
            });
          }
        )
      ],
    );
  }

  Widget setLocationUsage() {
    Future<SharedPreferences> preferences = SharedPreferences.getInstance();
    return Row(
      children: [
        Text('Use location services'),
        // white space
        Spacer(),
        FutureBuilder(
          future: preferences,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              bool useLocation = snapshot.data!.getBool('useLocation') ?? false;
              return Switch(
                value: useLocation,
                onChanged: setUseLocation,
              );
            } else {
              return CircularProgressIndicator();
            }
          }
        )
      ],
    );
  }

  void setUseLocation(bool newValue) async {
    await Permission.locationWhenInUse
      .onDeniedCallback(() {
        rootScaffoldMessengerKey.currentState!.showSnackBar(
          SnackBar(content: Text('Location services are required for this feature'))
        );
      })
      .onGrantedCallback(() {
        rootScaffoldMessengerKey.currentState!.showSnackBar(
          SnackBar(content: Text('Location services are now enabled'))
        );
        SharedPreferences.getInstance().then(
          (SharedPreferences prefs) {
            setState(() {
              prefs.setBool('useLocation', newValue);
            });
          }
        );
      })
      .onPermanentlyDeniedCallback(() {
        rootScaffoldMessengerKey.currentState!.showSnackBar(
          SnackBar(content: Text('Location services are required for this feature'))
        );
      })  
    .request();
  }

  Widget privacyInfo() {
    return Center(
      child: Column(
        children: [
          Text('AnyWay does not collect or store any of the data that is submitted via the app. The location of your trip is not stored. The location feature is only used to show your current location on the map, it is not transmitted to our servers.', textAlign: TextAlign.center),
          Padding(padding: EdgeInsets.only(top: 3)),
          Text('Our full privacy policy is available under:', textAlign: TextAlign.center),
          
          TextButton.icon(
            icon: Icon(Icons.info),
            label: Text(PRIVACY_URL),
            onPressed: () async{
              await launchUrl(Uri.parse(PRIVACY_URL));
            }
          )
        ],
      )
    );
  }

}
