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

import 'package:go_router/go_router.dart';

import 'package:fotodocumentation/controller/login_controller.dart';
import 'package:fotodocumentation/dto/jwt_token_pair_dto.dart';
import 'package:fotodocumentation/l10n/app_localizations.dart';
import 'package:fotodocumentation/pages/ui_utils/general_style.dart';
import 'package:fotodocumentation/utils/di_container.dart';
import 'package:fotodocumentation/utils/login_credentials.dart';

class LoginWidget extends StatefulWidget {
  const LoginWidget({super.key});

  @override
  State<LoginWidget> createState() => _LoginWidgetState();
}

class _LoginWidgetState extends State<LoginWidget> {
  LoginController get _loginController => DiContainer.get();
  LoginCredentials get _loginCredentials => DiContainer.get();
  GeneralStyle get _generalStyle => DiContainer.get();

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();

  String? _error;
  final FocusNode _focusNode = FocusNode();

  @override
  void dispose() {
    _focusNode.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _body(context),
    );
  }

  Widget _body(BuildContext context) {
    return Container(
      color: _generalStyle.pageBackgroundColor,
      child: _content(context),
    );
  }

  Widget _content(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: Form(
        key: _formKey,
        child: KeyboardListener(
          focusNode: _focusNode,
          onKeyEvent: (event) {
            if (event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.enter) {
              _actionSubmit(context);
            }
          },
          child: ListView(
            children: [
              Center(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 40.0),
                  child: Image.asset(
                    'assets/images/logo.png',
                    height: 120,
                  ),
                ),
              ),
              Center(
                child: ConstrainedBox(
                  constraints: const BoxConstraints(maxWidth: 500),
                  child: Card(
                    elevation: 0,
                    margin: EdgeInsets.zero,
                    clipBehavior: Clip.antiAlias,
                    child: Padding(
                      padding: const EdgeInsets.all(70.0),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Center(
                            child: Text(
                              AppLocalizations.of(context)!.loginTitle,
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: _generalStyle.primaryTextLabelColor,
                                fontFamily: _generalStyle.fontFamily,
                                fontSize: 50,
                              ),
                            ),
                          ),
                          const SizedBox(height: 40),
                          if (_error != null) ...[
                            Center(
                              child: Text(
                                _error!,
                                style: TextStyle(
                                  color: _generalStyle.errorColor,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16,
                                  fontFamily: _generalStyle.fontFamily,
                                ),
                              ),
                            ),
                            const SizedBox(height: 40),
                          ],
                          TextFormField(
                            key: Key("username"),
                            controller: _usernameController,
                            decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: _error != null ? BorderSide(color: _generalStyle.errorColor) : BorderSide(),
                              ),
                              enabledBorder: _error != null
                                  ? OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(8),
                                      borderSide: BorderSide(color: _generalStyle.errorColor),
                                    )
                                  : null,
                              labelText: AppLocalizations.of(context)!.loginUsernameTFLabel.toUpperCase(),
                              labelStyle: TextStyle(color: _generalStyle.primaryTextLabelColor, fontFamily: _generalStyle.fontFamily),
                              floatingLabelBehavior: FloatingLabelBehavior.always,
                              contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                            ),
                          ),
                          const SizedBox(height: 25),
                          TextFormField(
                            key: Key("password"),
                            controller: _passwordController,
                            obscureText: true,
                            decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: _error != null ? BorderSide(color: _generalStyle.errorColor) : BorderSide(),
                              ),
                              enabledBorder: _error != null
                                  ? OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(8),
                                      borderSide: BorderSide(color: _generalStyle.errorColor),
                                    )
                                  : null,
                              labelText: AppLocalizations.of(context)!.loginPasswordTFLabel.toUpperCase(),
                              labelStyle: TextStyle(color: _generalStyle.primaryTextLabelColor, fontFamily: _generalStyle.fontFamily),
                              floatingLabelBehavior: FloatingLabelBehavior.always,
                              contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                            ),
                          ),
                          const SizedBox(height: 25),
                          Center(
                            child: ElevatedButton(
                              key: Key("SubmitWidgetButton"),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: _generalStyle.primaryButtonBackgroundColor,
                                foregroundColor: _generalStyle.primaryButtonTextColor,
                                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
                              ),
                              onPressed: () async => await _actionSubmit(context),
                              child: Text(
                                AppLocalizations.of(context)!.loginLoginButtonLabel,
                                style: TextStyle(fontWeight: FontWeight.bold, fontFamily: _generalStyle.fontFamily),
                              ),
                            ),
                          ),
                          const SizedBox(height: 30),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _actionSubmit(BuildContext context) async {
    String username = _usernameController.text;
    String password = _passwordController.text;

    AuthenticateReply authenticateReply = await _loginController.authenticate(username, password);

    JwtTokenPairDto? jwtTokenPairDto = authenticateReply.jwtTokenPairDto;
    if (jwtTokenPairDto == null) {
      setState(() => _error = AppLocalizations.of(context)!.loginErrorMessage);
      return;
    }

    _loginCredentials.setLoggedIn(true);
    if (context.mounted) {
      context.go("/");
    }
  }
}
