import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/HomeScreen.dart';
import 'package:generp/services/api_calling.dart';
import 'package:generp/screens/LoginScreen.dart';

class UpdatePasswordProvider with ChangeNotifier {
  TextEditingController password = TextEditingController();
  TextEditingController confPassword = TextEditingController();

  String? passwordError;
  String? confirmPasswordError;

  bool isLoading = false;

  Future<void> updatePassword(BuildContext context) async {
    passwordError = null;
    confirmPasswordError = null;

    final pass = password.text.trim();
    final confPass = confPassword.text.trim();

    if (pass.isEmpty || pass.length < 8) {
      passwordError = pass.isEmpty ? "Enter Password" : "Password must be at least 8 characters";
    }
    if (confPass.isEmpty || confPass.length < 8) {
      confirmPasswordError = confPass.isEmpty ? "Enter Confirm Password" : "Confirm Password must be at least 8 characters";
    }
    if (pass != confPass) {
      confirmPasswordError = "Passwords do not match";
    }

    if (passwordError != null || confirmPasswordError != null) {
      notifyListeners();
      return;
    }

    isLoading = true;
    notifyListeners();

    try {
      final data = await ApiCalling.UpdatePasswordApi(empId, session, pass, confPass);
      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            toast(context, data.message);
            Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => MyHomePage()),
          );
          } else {
            toast(context, data.message);
          }
        } else {
          SharedpreferencesService().clearPreferences();
           Navigator.push(
                    context, MaterialPageRoute(builder: (context) => LoginScreen()));
        }
      }
    } catch (e) {
      toast(context, "Something went wrong");
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }
}
