import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '/components/custom_title_bar.dart';
import '/models/my_profile.dart';
import '/utils/storage/database.dart';

@immutable
class ChangeServerUrl extends StatefulWidget {
  const ChangeServerUrl({
    Key? key,
  }) : super(key: key);

  @override
  State<ChangeServerUrl> createState() => _ChangeServerUrl();
}

class _ChangeServerUrl extends State<ChangeServerUrl> {
  final _formKey = GlobalKey<FormState>();

  final TextEditingController _serverUrlController = TextEditingController();

  bool invalidCurrentPassword = false;

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

  Future<void> setUrl() async {
    final preferences = await SharedPreferences.getInstance();
    _serverUrlController.text = preferences.getString('server_url') ?? defaultServerUrl;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const CustomTitleBar(
        title: Text(
          'Profile',
          style: TextStyle(
            fontSize: 32,
            fontWeight: FontWeight.bold
          )
        ),
        showBack: true,
        backgroundColor: Colors.transparent,
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Form(
            key: _formKey,
            child: Padding(
              padding: const EdgeInsets.only(
                left: 20,
                right: 20,
                top: 30,
              ),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const Text(
                      'Change Server Url',
                      style: TextStyle(
                        fontSize: 25,
                      ),
                    ),
                    const SizedBox(height: 30),
                    showWarning(),
                    const SizedBox(height: 30),
                    TextFormField(
                      controller: _serverUrlController,
                      decoration: const InputDecoration(
                          hintText: 'Server Url',
                      ),
                      // The validator receives the text that the user has entered.
                      validator: (String? value) {
                        if (value == null || !Uri.parse(value).isAbsolute) {
                          return 'Invalid URL';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 15),
                    ElevatedButton(
                      onPressed: () {
                        if (!_formKey.currentState!.validate()) {
                          return;
                        }

                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('Processing Data')),
                        );

                      },
                      child: const Text('CHANGE SERVER URL'),
                  ),
                ],
              )
            )
          )
        )
      )
    );
  }

  Widget showWarning() {
    String warning1 = '''
WARNING: Do not use this feature unless you know what you\'re doing!
''';

    String warning2 = '''
Changing the server url will disconnect you from all friends and conversations on this server, and connect you to a fresh environment. This feature is intended to be used by people that are willing to host their own Capsule server, which you can find by going to \nhttps://github.com/SomeUsername/SomeRepo.\n\n
You can revert this by entering \nhttps://envelope-messenger.com\n on the login screen.
''';

    return Column(
      children: [
        Text(
          warning1,
          textAlign: TextAlign.center,
          style: TextStyle(
            color: Theme.of(context).colorScheme.error,
          )
        ),
        Text(
          warning2,
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  // TODO: Write user data to new server??
  Future<void> changeUrl() async {
    MyProfile.setServerUrl(_serverUrlController.text);
    deleteDb();
    MyProfile.logout();
    Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing'));
  }
}
