//older code...

// import 'package:flutter/material.dart';
// import 'package:fluttertoast/fluttertoast.dart';
// import 'package:provider/provider.dart';
// import 'package:shared_preferences/shared_preferences.dart';
// import 'package:test_sa/controllers/providers/settings/app_settings.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>();
//
//   bool rememberMe = false;
//
//   @override
//   Widget build(BuildContext context) {
//     _userProvider = Provider.of<UserProvider>(context);
//     if (_settingProvider == null) {
//       _settingProvider = Provider.of<SettingProvider>(context);
//       rememberMe = _settingProvider.rememberMe;
//       if (rememberMe) {
//         _user.userName = _settingProvider.username;
//         _user.password = _settingProvider.password;
//       }
//     }
//
//     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;
//                     },
//                   ),
//                   8.height,
//                   Row(
//                     children: [
//                       Checkbox(
//                           value: rememberMe,
//                           activeColor: AppColor.blueStatus(context),
//                           onChanged: (value) {
//                             setState(() {
//                               rememberMe = value;
//                             });
//                           }),
//                       "Remember Me".bodyText(context).custom(color: context.isDark ? AppColor.primary50 : AppColor.neutral50).expanded,
//                     ],
//                   ),
//                   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) {
//       await _settingProvider.setUser(_userProvider.user);
//       (await SharedPreferences.getInstance()).remove(ASettings.localAuth);
//       await _settingProvider.setRememberMe(_user.userName, _user.password, rememberMe);
//
//       /// 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);
//     }
//   }
// }

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:test_sa/app_strings/app_asset.dart';
import 'package:test_sa/controllers/notification/firebase_notification_manger.dart';
import 'package:test_sa/controllers/providers/settings/app_settings.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();
  late UserProvider _userProvider;
  SettingProvider? _settingProvider;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  bool rememberMe = false;

  @override
  void initState() {
    super.initState();
    if (FirebaseNotificationManger.token == null) FirebaseNotificationManger.getToken();
  }

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    if (_settingProvider == null) {
      _settingProvider = Provider.of<SettingProvider>(context);
      rememberMe = _settingProvider!.rememberMe;
      if (rememberMe) {
        _user.userName = _settingProvider!.username;
        _user.password = _settingProvider!.password;
      }
    }

    return Form(
      key: _formKey,
      child: Scaffold(
          backgroundColor: AppColor.background(context),
          body: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: double.infinity,
                  height: 293.toScreenHeight,
                  padding: EdgeInsets.only(left: 16.toScreenWidth),
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(AppAsset.loginTopBg),
                      fit: BoxFit.cover, // Adjusts the image to cover the entire container
                    ),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      SizedBox(
                        height: 146.toScreenHeight,
                      ),
                      // RoundedBackButton(
                      //     icon: Icons.arrow_back_ios,
                      //     onPressed: () {
                      //       ///There is no previous screen
                      //     },
                      //     backgroundColor: context.isDark ? AppColor.primary80 : AppColor.primary80),

                      context.translation.signInToYour.customHeadingText(context).custom(color: Colors.white, fontSize: 27, fontWeight: FontWeight.w500),
                      context.translation.account.customHeadingText(context).custom(color: Colors.white, fontSize: 27, fontWeight: FontWeight.w500),
                      25.height,
                      context.translation.letSignInToAccount.customHeadingText(context).custom(color: Colors.white, fontWeight: FontWeight.w500, fontSize: 12),
                    ],
                  ),
                ),
                SizedBox(
                  height: 47.toScreenHeight,
                ),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      AppTextFormField(
                        initialValue: _user.userName ?? "",
                        backgroundColor: AppColor.white20,
                        validator: (value) => Validator.hasValue(value!) ? null : context.translation.requiredField,
                        labelText: context.translation.username,
                        style: TextStyle(fontWeight: FontWeight.w500, fontSize: 12, color: Color(0xff3B3D4A)),
                        labelStyle: TextStyle(fontWeight: FontWeight.w500, fontSize: 11, color: Color(0xff767676)),
                        textInputType: TextInputType.text,
                        showWithoutDecoration: true,
                        contentPadding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 12.toScreenHeight),
                        onSaved: (value) {
                          _user.userName = value;
                        },
                      ),
                      18.height,
                      AppTextFormField(
                        initialValue: _user.password ?? "",
                        showWithoutDecoration: true,
                        labelText: context.translation.password,
                        backgroundColor: AppColor.white20,
                        style: TextStyle(fontWeight: FontWeight.w500, fontSize: 12, color: Color(0xff3B3D4A)),
                        labelStyle: TextStyle(fontWeight: FontWeight.w500, fontSize: 11, color: Color(0xff767676)),
                        contentPadding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 12.toScreenHeight),
                        obscureText: true,
                        validator: (value) => Validator.isValidPassword(value!)
                            ? null
                            : value.isEmpty
                                ? context.translation.requiredField
                                : context.translation.passwordLengthMessage,
                        onSaved: (value) {
                          _user.password = value;
                        },
                      ),
                      8.height,
                      // Align(
                      //   alignment: AlignmentDirectional.centerEnd,
                      //   child: InkWell(
                      //     onTap: () {
                      //       /// TODO [zaid] : push to another screen
                      //     },
                      //     child: context.translation.forgotPassword.bodyText(context).custom(color: AppColor.primary10, fontWeight: FontWeight.w500),
                      //   ),
                      // ),
                      Row(
                        children: [
                          Checkbox(
                              value: rememberMe,
                              activeColor: AppColor.blueStatus(context),
                              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              onChanged: (value) {
                                setState(() {
                                  rememberMe = value!;
                                });
                              }),
                          "Remember Me".bodyText(context).custom(color: context.isDark ? AppColor.primary50 : AppColor.neutral50).expanded,
                        ],
                      ),
                      50.height,
                      AppFilledButton(label: context.translation.signIn, buttonColor: AppColor.primary10, maxWidth: true, onPressed: _login),
                    ],
                  ),
                ),
              ],
            ),
          )),
    );
  }

  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) {
      await _settingProvider!.setUser(_userProvider.user!);
      (await SharedPreferences.getInstance()).remove(ASettings.localAuth);
      await _settingProvider!.setRememberMe(_user.userName!, _user.password!, rememberMe);

      /// 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);
    }
  }
}
