part of '../pages.dart';

final user = RM.injectAuth<AuthModel?, LoginParam>(
  () => AuthRepository(),
  persist: () => PersistState<AuthModel?>(
    key: '__AuthModel__',
    toJson: (user) => user!.toJson(),
    fromJson: (json) {
      final user = AuthModel.fromJson(json);
      return user.data!.token != null ? user : null;
    },
    debugPrintOperations: true,
  ),
  autoSignOut: (user) {
    if (user!.data == null) {
      return Duration(seconds: 5);
    }
    return Duration(days: 3);
  },
  onSetState: On.error(
    (error, refresh) {
      String err = checkError(error.toString());
      showToastWidget(
        err,
        duration: 'long'
      );
    },
  ),
);

final RegExp _passwordRegExp = RegExp(
  r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$',
);

final RegExp _emailRegExp = RegExp(
  r'^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$',
);

final _email = RM.injectTextEditing(
  validator: (email) {
    if (!_emailRegExp.hasMatch(email!)) {
      return "Enter a valid email";
    }
  },
);
final _password = RM.injectTextEditing(
  validateOnTyping: true,
  validator: (password) {
    if (password!.length < 4) {
      return "Enter a valid password";
    }
  },
);

final _form = RM.injectForm(
  submit: () async {
    await user.auth.signIn(
      (_) => LoginParam(
        email: _email.text,
        password: _password.text,
      ),
      onError: (error, refresh) {
        showToastWidget(
          error.message,
          duration: 'long'
        );
      }
    );
    if (user.error != null) {
      showToastWidget(
        user.error.message,
        duration: 'long'
      );
    }
  },
);

class AuthException implements Exception {
  final String message;
  AuthException(this.message);
}

class LoginPage extends StatelessWidget {
  const LoginPage({Key? key}) : super(key: key);
  static const routeName = '/login_page';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(10),
        child: On.form(
          () => Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              TextField(
                key: Key('__EmailField__'),
                controller: _email.controller,
                focusNode: _email.focusNode,
                decoration: InputDecoration(
                  icon: Icon(Icons.email),
                  labelText: "Email",
                  errorText: _email.error,
                ),
                keyboardType: TextInputType.emailAddress,
                autocorrect: false,
                onSubmitted: (_) {
                  _password.focusNode.requestFocus();
                },
              ),
              TextField(
                key: Key('__PasswordField__'),
                controller: _password.controller,
                focusNode: _password.focusNode,
                decoration: InputDecoration(
                  icon: Icon(Icons.lock),
                  labelText: "Password",
                  errorText: _password.error,
                ),
                obscureText: true,
                autocorrect: false,
                onSubmitted: (_) {
                  _form.submitFocusNode.requestFocus();
                },
              ),
              SizedBox(height: 10),
              On.formSubmission(
                onSubmitting: () => const Center(
                  child: CircularProgressIndicator(),
                ),
                child: ElevatedButton(
                  focusNode: _form.submitFocusNode,
                  child: Text("Sign in"),
                  onPressed: _form.submit,
                ),
              ).listenTo(_form),
              SizedBox(height: 10),
              SelectableText("email : ${SharedValue.email}"),
              SelectableText("password : ${SharedValue.password}"),
            ],
          ),
        ).listenTo(_form)
      )
    );
  }
}