import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/api/api_auth_repository.dart';
import 'package:telnow_mobile_new/src/injector/injector.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/model/login/login_body.dart';
import 'package:telnow_mobile_new/src/model/token/token.dart';
import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/extensions.dart';

class WebPasswordPage extends StatefulWidget {
  final Map<String, dynamic> user;
  const WebPasswordPage({required this.user, super.key});

  @override
  State<WebPasswordPage> createState() => _WebPasswordPageState();
}

class _WebPasswordPageState extends State<WebPasswordPage> {
  final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  final ApiAuthRepository apiAuthRepository = ApiAuthRepository();
  final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();

  String controllerOld = '';
  String controllerNew = '';
  String controllerConfirm = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor,
      appBar: PreferredSize(preferredSize: Size.fromHeight(0), child: AppBar(elevation: 0, backgroundColor: primaryColor)),
      body: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('settingPassword'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                GestureDetector(
                  child: Text('buttonBack'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                  onTap: ()=>navigateBack(context),
                ).withHover(),
              ],
            ),
          ),
          divider(),
          Expanded(
            child: SingleChildScrollView(
              padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
              child: Row(
                children: [
                  Container(
                    alignment: Alignment.topLeft,
                    width: MediaQuery.of(context).size.width/3,
                    padding: EdgeInsets.all(20),
                    decoration: BoxDecoration(color: Colors.white, border: Border.all(color: textColor.withValues(alpha: 0.15)), borderRadius: BorderRadius.all(Radius.circular(12))),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          margin: EdgeInsets.only(bottom: 5),
                          child: Text('titlePassOld'.tr(), style: TextStyle(fontSize: 16, color: textColor)),
                        ),
                        passwordFieldTemplate(value: controllerOld, iconColor: textColor.withValues(alpha: 0.5), color: textColor, placeholder: 'oldPassword'.tr(), action: (val)=>controllerOld=val),

                        Container(
                            margin: EdgeInsets.only(top: 30, bottom: 5),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text('titlePassNew'.tr(), style: TextStyle(fontSize: 16, color: textColor)),
                                SizedBox(height: 30),
                                Text('newPassword'.tr(), style: TextStyle(fontSize: 16, color: textColor)),
                              ],
                            )
                        ),
                        passwordFieldTemplate(value: controllerNew, placeholder: 'newPassword'.tr(), action: (val)=>controllerNew=val),

                        Container(
                          margin: EdgeInsets.only(top: 20, bottom: 5),
                          child: Text('confirmPassword'.tr(), style: TextStyle(fontSize: 16, color: textColor)),
                        ),
                        passwordFieldTemplate(value: controllerConfirm, placeholder: 'confirmPassword'.tr(), action: (val)=>controllerConfirm=val),

                        SizedBox(height: 50),
                        buttonTemplate(text: 'buttonSave'.tr(), action: ()async{
                          if(controllerOld.trim().isNotEmpty && controllerNew.trim().isNotEmpty && controllerConfirm.trim().isNotEmpty){
                            if(controllerNew == controllerConfirm){
                              var data = {
                                'oldPassword':controllerOld.trim(),
                                'password':controllerNew.trim()
                              };

                              var res = await apiAuthProvider.patchData('/api/informants/'+widget.user['id'].toString()+'/changePassword', data);
                              if(res != null){
                                String username = widget.user['_isRelated']?widget.user['relatedTo']:widget.user['userId'];
                                String? password = widget.user['_isRelated'] && widget.user['tenantCode']!=null && widget.user['tenantCode']!=''?widget.user['tenantCode']+' '+data['password']:data['password'];

                                LoginBody loginBody = LoginBody(username, password!, 'password');
                                Token token = await apiAuthRepository.postLoginUser(loginBody);
                                if (token.error != null) {
                                  showError(context, token.error);
                                }
                                else{
                                  await sharedPreferencesManager.putString(SharedPreferencesManager.keyAccessToken, token.accessToken!);
                                  await sharedPreferencesManager.putString(SharedPreferencesManager.keyRefreshToken, token.refreshToken!);
                                  await sharedPreferencesManager.putString(SharedPreferencesManager.keyUsername, widget.user['_isRelated']?widget.user['tenantCode']!=null && widget.user['tenantCode']!=''?widget.user['tenantCode']+' '+data['password']!:data['password']!:widget.user['userId']);
                                  Navigator.of(context).pop(true);
                                }
                              }
                            }
                            else{
                              showError(context, 'checkNewPass'.tr());
                            }
                          }
                          else{
                            showError(context, 'cannotEmpty'.tr());
                          }
                        })
                      ],
                    ),
                  ),
                  Expanded(child: Container())
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget passwordFieldTemplate({required String value, iconColor = primaryColor, Color color = primaryColor, placeholder = '', required action(value)}){
    TextEditingController controller = TextEditingController()..text = value;
    bool hidePass = true;
    return SizedBox(
      width: double.infinity,
      child: StatefulBuilder(
        builder: (context, fieldState) => TextFormField(
          controller: controller,
          style: TextStyle(fontSize: 16, color: color),
          keyboardType: widget.user['_isRelated']?TextInputType.number:null,
          inputFormatters: widget.user['_isRelated']?[FilteringTextInputFormatter.digitsOnly]:null,
          enableInteractiveSelection: widget.user['_isRelated']?false:true,
          obscureText: hidePass,
          decoration: InputDecoration(
              hintText: placeholder,
              hintStyle: TextStyle(fontSize: 16, color: color.withValues(alpha: 0.5)),
              filled: true,
              fillColor: Colors.white,
              hoverColor: textColor.withValues(alpha: 0.1),
              contentPadding: EdgeInsets.all(16),
              border: InputBorder.none,
              prefixIcon: U.iconsax('bold/key', size: 24, color: iconColor),
              suffixIconConstraints: BoxConstraints(maxHeight: 40, maxWidth: 40, minHeight: 40, minWidth: 40),
              suffixIcon: GestureDetector(child: U.iconsax(hidePass?'eye':'eye-slash', size: 24, color: textColor.withValues(alpha: 0.5)), onTap: ()=>fieldState(()=>hidePass=!hidePass)).withHover(),
              enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: textColor.withValues(alpha: 0.5))),
              focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: textColor.withValues(alpha: 0.5))),
              isDense: true
          ),
          onChanged: (val)=>action(val.toString()),
        ),
      ),
    );
  }
}
