import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/pages/land_page/land_page.dart';

import '../../controllers/providers/api/user_provider.dart';
import '../../controllers/providers/settings/setting_provider.dart';
import '../../controllers/validator/validator.dart';
import '../../models/user.dart';
import '../common_widgets/app_filled_button.dart';
import '../common_widgets/app_text_form_field.dart';

class LoginPage extends StatefulWidget {
  static const String routeName = "/login_page";

  const LoginPage({Key key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final User _user = User();
  UserProvider _userProvider;
  SettingProvider _settingProvider;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);

    return Form(
      key: _formKey,
      child: Scaffold(
        body: Column(
          children: [
            SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Hero(tag: "logo", child: "logo".toSvgAsset(height: 64)),
                  64.height,
                  context.translation.login.heading2(context).custom(fontWeight: FontWeight.w600, color: context.isDark ? AppColor.primary50 : AppColor.neutral50),
                  context.translation.enterCredsToLogin.heading6(context).custom(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20),
                  32.height,
                  AppTextFormField(
                    initialValue: _user?.userName,
                    validator: (value) => Validator.hasValue(value) ? null : context.translation.requiredField,
                    labelText: context.translation.username,
                    textInputType: TextInputType.text,
                    onSaved: (value) {
                      _user.userName = value;
                    },
                  ),
                  16.height,
                  AppTextFormField(
                    initialValue: _user?.password,
                    labelText: context.translation.password,
                    obscureText: true,
                    validator: (value) => Validator.isValidPassword(value)
                        ? null
                        : value.isEmpty
                            ? context.translation.requiredField
                            : context.translation.passwordLengthMessage,
                    onSaved: (value) {
                      _user.password = value;
                    },
                  ),
                  16.height,
                  Align(
                    alignment: AlignmentDirectional.centerEnd,
                    child: InkWell(
                      onTap: () {
                        /// TODO [zaid] : push to another screen
                      },
                      child: context.translation.forgotPassword.bodyText(context).custom(color: AppColor.primary50, fontWeight: FontWeight.w500),
                    ),
                  ),
                ],
              ),
            ).center.expanded,
            AppFilledButton(label: context.translation.login, maxWidth: true, onPressed: _login),
          ],
        ).paddingOnly(start: 16, end: 16, bottom: 24, top: 24),
      ),
    );
  }

  Future<void> _login() async {
    if (!_formKey.currentState.validate()) return;
    _formKey.currentState.save();
    int status = await _userProvider.login(context: context, user: _user);
    if (status >= 200 && status < 300 && _userProvider.user.isAuthenticated ?? false) {
      _settingProvider.setUser(_userProvider.user);

      /// The below line for the new design
      // Navigator.pushNamed(context, LandPage.routeName);
      Navigator.pushNamed(context, LandPage.routeName);
    } else {
      Fluttertoast.showToast(msg: _userProvider.user?.message ?? context.translation.failedToCompleteRequest);
    }
  }
}
