import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hmg_flutter_template/classes/colors.dart';
import 'package:hmg_flutter_template/classes/consts.dart';
import 'package:hmg_flutter_template/classes/enums.dart';
import 'package:hmg_flutter_template/classes/utils.dart';
import 'package:hmg_flutter_template/config/routes.dart';
import 'package:hmg_flutter_template/extensions/string_extensions.dart';
import 'package:hmg_flutter_template/extensions/widget_extensions.dart';
import 'package:hmg_flutter_template/extensions/int_extensions.dart';
import 'package:hmg_flutter_template/generated/locale_keys.g.dart';
import 'package:hmg_flutter_template/main.dart';
import 'package:hmg_flutter_template/model/login/imei_details_model.dart';
import 'package:hmg_flutter_template/model/login/member_login_model.dart';
import 'package:hmg_flutter_template/model/login/project_info_model.dart';
import 'package:hmg_flutter_template/provider/login_provider_model.dart';
import 'package:hmg_flutter_template/widgets/button/default_button.dart';
import 'package:hmg_flutter_template/widgets/cupertino_picker.dart';
import 'package:hmg_flutter_template/widgets/input_widget.dart';
import 'package:injector/injector.dart';
import 'package:local_auth/local_auth.dart';
import 'package:provider/provider.dart';
import 'package:sizer/sizer.dart';

class LoginPage extends StatefulWidget {
  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  int branchID = 0;

  LoginProviderModel? provider;

  final loginFormKey = GlobalKey<FormState>();

  var projectIdController = TextEditingController();

  var userIdController = TextEditingController();

  var passwordController = TextEditingController();

  checkUserSession() async {
    provider!.checkLastSession();
  }

  setUserSession() async {
    await Utils.getStringFromPrefs(SharedPrefsConsts.username);
    await Utils.getStringFromPrefs(SharedPrefsConsts.password);
  }

  @override
  Widget build(BuildContext context) {
    if (provider == null) {
      dynamic? isNeedCheckUserSession = (ModalRoute.of(context)!.settings.arguments);
      // setUserSession();
      provider = context.read<LoginProviderModel>();
      if (isNeedCheckUserSession == null) {
        checkUserSession();
      }
    }

    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: SizedBox(
                  height: MediaQuery.of(context).size.height / 1.2,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                        flex: 1,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            LocaleKeys.welcomeTo.tr().toText14(color: MyColors.blackColor),
                            LocaleKeys.drSulaiman.tr().toText20(isBold: true, color: MyColors.blackColor),
                            "Nurses App".toText16(color: MyColors.redColor),
                          ],
                        ),
                      ),
                      Expanded(
                        flex: 3,
                        child: Form(
                          key: loginFormKey,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              CustomTextField(
                                LocaleKeys.userID.tr(),
                                userIdController,
                                isEnableBorder: true,
                                isInputTypeNum: true,
                              ),
                              16.height,
                              CustomTextField(
                                LocaleKeys.password.tr(),
                                passwordController,
                                isTextIsPassword: true,
                                onChange: (v) {
                                  if (v.length == 1) {
                                    provider!.getAssignedBranches(userIdController.text);
                                  }
                                },
                              ),
                              16.height,
                              Consumer<LoginProviderModel>(
                                builder: (_, data, w) {
                                  // if (data.state == ViewState.idle && provider.assignedBranches.isNotEmpty) {
                                  //   projectIdController.text = provider.assignedBranches.first.facilityName!;
                                  //   branchID = provider.assignedBranches.first.facilityId as int;
                                  //   print(branchID);
                                  //   provider.notifyListeners();
                                  // }
                                  return data.state == ViewState.hide
                                      ? Container()
                                      : data.state == ViewState.busy
                                          ? const Center(child: CircularProgressIndicator())
                                          : CustomTextField(
                                              LocaleKeys.branch.tr(),
                                              projectIdController,
                                              hasSelection: true,
                                              isEnable: false,
                                              onClick: () => CustomCupertinoPicker.showCupertinoPicker(
                                                context,
                                                provider!.assignedBranches,
                                                (index) {
                                                  projectIdController.text = provider!.assignedBranches[index].facilityName!;
                                                  branchID = provider!.assignedBranches[index].facilityId as int;
                                                  provider!.notifyListeners();
                                                },
                                              ),
                                            );
                                },
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            21.height,
            DefaultButton(
              LocaleKeys.login.tr(),
              () async {
                // provider.checkLastSession();
                bool isSuccess = await provider!.performLogin(userIdController.text, passwordController.text, branchID);
                if (isSuccess) {
                  appState.password = passwordController.text;
                  appState.doctorUserId = int.parse(userIdController.text);
                  print(appState.doctorUserId);
                }
              },
              colors: const [
                MyColors.redColor,
                MyColors.redColor,
              ],
            ),
          ],
        ).paddingAll(21),
      ),
    );
  }
}
