import 'dart:developer' as developer;

import 'package:flutter/material.dart';
import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:skillcourt/entity/user_info.dart';
import 'package:skillcourt/services/http_service.dart';
import 'package:skillcourt/widgets/text_field.dart';

final _messangerKey = GlobalKey<ScaffoldMessengerState>();
Color _white = const Color(0xFFFFFFFF);

class UserRegistration extends StatefulWidget {
  static const routeName = 'user-registration';

  const UserRegistration({Key? key}) : super(key: key);

  @override
  _UserRegistrationState createState() => _UserRegistrationState();
}

class _UserRegistrationState extends State<UserRegistration> {
  //textinput related
  final firstName = TextEditingController();
  final lastName = TextEditingController();
  final birthDate = TextEditingController();
  final userName = TextEditingController();
  final phoneNumber = TextEditingController();
  final email = TextEditingController();
  final password = TextEditingController();
  final confirmPassword = TextEditingController();

  final validCharacters = RegExp(r'^[a-zA-Z0-9_\-=@,\.;]+$');
  final validEmail = RegExp(
      r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$');

  PhoneNumber number = PhoneNumber(isoCode: 'US');
  final EdgeInsetsGeometry _defaultEdgeInsets =
      const EdgeInsets.symmetric(horizontal: 0.0, vertical: 5.0);
  Future<UserInfo>? _futureUserInfo;

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    email.dispose();
    password.dispose();
    confirmPassword.dispose();
    firstName.dispose();
    lastName.dispose();
    birthDate.dispose();
    userName.dispose();
    phoneNumber.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: PlatformAppBar(),
      body: Stack(
        children: <Widget>[
          Container(
              height: double.infinity,
              width: double.infinity,
              color: const Color(0xFF2E7D32)),
          Column(children: [
            Expanded(
              flex: 1,
              child: Padding(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 15.0, vertical: 0.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        'Create user',
                        style: TextStyle(
                          color: _white,
                          fontSize: 30.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Padding(
                          padding: _defaultEdgeInsets,
                          child: _buildInputField(
                              controller: userName, label: 'Enter Username')),
                      Padding(
                          padding: _defaultEdgeInsets,
                          child: _buildInputField(
                              controller: firstName,
                              label: 'Enter First Name')),
                      Padding(
                          padding: _defaultEdgeInsets,
                          child: _buildInputField(
                              controller: lastName, label: 'Enter Last Name')),
                      Padding(
                          padding: _defaultEdgeInsets,
                          child: _buildInputField(
                              controller: email, label: 'Email')),
                      Padding(
                        padding: _defaultEdgeInsets,
                        child: CustomTextField(
                            labelText: 'Date of Birth',
                            hintText: 'Enter Date of Birth',
                            controller: birthDate,
                            onTap: () async {
                              FocusScope.of(context).requestFocus(FocusNode());
                              final date = await showDatePicker(
                                  context: context,
                                  initialDate: DateTime.now(),
                                  firstDate: DateTime(1900),
                                  lastDate: DateTime.now());
                              if (date != null) {
                                birthDate.text = date.toLocal().toString();
                              }
                            }),
                      ),
                      Padding(
                          padding: _defaultEdgeInsets,
                          child: InternationalPhoneNumberInput(
                              onInputChanged: (PhoneNumber number) {
                                setState(() {
                                  this.number = number;
                                });
                              },
                              hintText: 'Enter your phone number',
                              textFieldController: phoneNumber,
                              initialValue: number)),
                      Padding(
                          padding: _defaultEdgeInsets,
                          child: _buildInputField(
                              controller: password,
                              label: 'Password',
                              obscureText: true)),
                      Padding(
                          padding: _defaultEdgeInsets,
                          child: _buildInputField(
                              controller: confirmPassword,
                              label: 'Confirm Password',
                              obscureText: true)),
                      _buildButton(
                          label: 'Sign Up',
                          onPressed: () async {
                            developer.log(confirmPassword.text,
                                name: 'my.app.category');
                            setState(() {
                              validator:
                              {
                                if (userName.text.isEmpty) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content:
                                              Text('Please add a username')));
                                } else if (firstName.text.isEmpty) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content:
                                              Text('Please add a first name')));
                                } else if (lastName.text.isEmpty) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content:
                                              Text('Please add a last name')));
                                } else if (email.text.isEmpty) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content: Text(
                                              'Please add an email address')));
                                } else if (!validEmail.hasMatch(email.text)) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content: Text(
                                              'Please enter a valid email address')));
                                } else if (birthDate.text.isEmpty) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content:
                                              Text('Please add a birth date')));
                                } else if (phoneNumber.text.isEmpty) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content: Text(
                                              'Please add a phone number')));
                                } else if (phoneNumber.text.length != 12) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content: Text(
                                              'The phone number is not valid. Please enter a valid phone number')));
                                } else if (confirmPassword.text !=
                                    password.text) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content: Text(
                                              'The passwords do not match, Please Try Again')));
                                } else if (password.text.isEmpty) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content:
                                              Text('Please add a password')));
                                } else if (password.text.length < 8) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content: Text(
                                              'Password length must be at least 8 characters')));
                                } else if (!validCharacters
                                    .hasMatch(password.text)) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content: Text(
                                              'Password contains invalid character. Make sure your password only has ')));
                                } else if (!password.text
                                    .contains(RegExp('[A-Z]'))) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content: Text(
                                              'Password needs at least one uppercase character. ')));
                                } else if (!password.text
                                    .contains(RegExp('[a-z]'))) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content: Text(
                                              'Password needs at least one lowercase character. ')));
                                } else if (!password.text
                                        .contains(RegExp('[0-9]')) &&
                                    !password.text.contains(
                                        RegExp(r'[!@#$%^&*(),.?":{}|<>]'))) {
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content: Text(
                                              'Password should contain either one digit or special character.')));
                                } else {
                                  _futureUserInfo = HttpService.createUser(
                                      email.text,
                                      password.text,
                                      firstName.text,
                                      lastName.text,
                                      birthDate.text,
                                      phoneNumber.text,
                                      userName.text);
                                  _messangerKey.currentState?.showSnackBar(
                                      const SnackBar(
                                          content: Text('User created!')));
                                }
                              }
                            });
                            SharedPreferences prefs =
                                await SharedPreferences.getInstance();

                            prefs.setString('userEmail', email.text);
                            prefs.setString('userName', userName.text);
                            prefs.setString('firstName', firstName.text);
                            prefs.setString('lastName', lastName.text);
                            prefs.setString('phoneNumber', phoneNumber.text);
                          })
                    ],
                  )),
            ),
            const Padding(
                padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 10.0),
                child: Text(
                  '© 2021 skillcourt. | All rights reserved',
                  style: TextStyle(
                      color: Color(0xFFFFFFFF), fontWeight: FontWeight.bold),
                ))
          ]),
        ],
      ),
    );
  }

  Padding _buildButton(
      {required String label, required VoidCallback? onPressed}) {
    return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 15.0),
        child: SizedBox(
            width: double.infinity,
            height: 50.0,
            child: PlatformTextButton(
              color: const Color.fromARGB(255, 15, 67, 17),
              onPressed: onPressed,
              child: PlatformText(
                label,
                style: TextStyle(
                    color: _white,
                    letterSpacing: 2.0,
                    fontSize: 18.0,
                    fontWeight: FontWeight.bold),
              ),
            )));
  }

  PlatformTextField _buildInputField(
      {required TextEditingController controller,
      required String label,
      bool obscureText = false}) {
    return PlatformTextField(
        obscureText: obscureText,
        material: (_, __) => MaterialTextFieldData(
            controller: controller,
            maxLines: 1,
            style: const TextStyle(color: Colors.white),
            decoration: InputDecoration(
              labelText: label,
              labelStyle: const TextStyle(color: Colors.white),
            )),
        cupertino: (_, __) => CupertinoTextFieldData(
            controller: controller, maxLines: 1, placeholder: label));
  }
}
