import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:tm_app/data/services/model/customer/customer.dart';
import 'package:tm_app/data/services/model/forgot_password_response/forgot_password_response_model.dart';
import 'package:tm_app/data/services/model/verify_otp_response/verify_otp_response_model.dart';

import '../core/utils/result.dart';
import '../data/repositories/auth_repository.dart';
import '../data/services/model/login_response/login_response_model.dart';
import '../data/services/model/logout_response/logout_response.dart';
import '../data/services/model/reset_password_response/reset_password_response.dart';

class AuthViewModel with ChangeNotifier {
  final AuthRepository _authRepository;

  AuthViewModel({required AuthRepository authRepository})
    : _authRepository = authRepository {
    usernameController.addListener(_onTextChanged);
    passwordController.addListener(_onTextChanged);
    emailController.addListener(_onTextChanged);
    otpController.addListener(_onTextChanged);
    newPasswordController.addListener(_onTextChanged);
  }

  final TextEditingController usernameController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController newPasswordController = TextEditingController();
  final TextEditingController otpController = TextEditingController();

  final FocusNode usernameFocus = FocusNode();
  final FocusNode passwordFocus = FocusNode();
  final FocusNode emailFocus = FocusNode();
  final FocusNode newPasswordFocus = FocusNode();
  final FocusNode otpFocus = FocusNode();

  bool _obscurePassword = true;
  bool get obscurePassword => _obscurePassword;

  bool _obscureForgotPassword = true;
  bool get obscureForgotPassword => _obscureForgotPassword;

  bool get isLoginEnabled =>
      usernameController.text.isNotEmpty && passwordController.text.isNotEmpty;

  // Auth state
  bool _isLoading = false;
  bool _isResetPasswordLoading = false;
  String? _errorMessage;
  String? _resetPasswordErrorMessage;
  Customer? _loggedInUser;
  String? successMessage;
  String? _forgotPasswordMessage;
  bool _isLoadingForgot = false;
  bool _isLoadingOtp = false;
  String? _errorMessageForget;
  String? _errorMessageOtp;

  bool get isLoading => _isLoading;
  bool get isLoadingForgot => _isLoadingForgot;
  bool get isLoadingOtp => _isLoadingOtp;
  bool get isResetPasswordLoading => _isResetPasswordLoading;
  String? get errorMessage => _errorMessage;
  String? get errorMessageForget => _errorMessageForget;
  String? get resetPasswordErrorMessage => _resetPasswordErrorMessage;
  String? get errorMessageOtp => _errorMessageOtp;

  Customer? get loggedInUser => _loggedInUser;
  String? get forgotPasswordMessage => _forgotPasswordMessage;
  String? resetToken;

  void togglePasswordVisibility() {
    _obscurePassword = !_obscurePassword;
    notifyListeners();
  }

  void toggleForgotPasswordVisibility() {
    _obscureForgotPassword = !_obscureForgotPassword;
    notifyListeners();
  }

  bool get isEmailValid {
    final email = emailController.text.trim();
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    return emailRegex.hasMatch(email);
  }

  bool get isOtpValid {
    final otp = otpController.text.trim();
    return otp.length == 5;
  }

  bool get canSubmitOtpPage {
    return isOtpValid;
  }

  bool get isNewPasswordValid {
    final password = newPasswordController.text.trim();

    final hasMinLength = password.length >= 5;
    final hasUppercase = RegExp(r'[A-Z]').hasMatch(password);
    final hasLowercase = RegExp(r'[a-z]').hasMatch(password);
    final hasSpecialChar = RegExp(r'[!@#\$%&\*\^]').hasMatch(password);

    return hasMinLength && hasUppercase && hasLowercase && hasSpecialChar;
  }

  void _onTextChanged() {
    notifyListeners();
  }

  Future<void> login() async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    await localLogout();

    final result = await _authRepository.login(
      username: usernameController.text.trim(),
      password: passwordController.text.trim(),
    );

    switch (result) {
      case Ok<LoginResponseModel>():
        _loggedInUser = result.value.data.customer;
        usernameController.clear();
        passwordController.clear();
        break;
      case Error<LoginResponseModel>():
        _errorMessage = result.error.toString();
        break;
    }

    _isLoading = false;
    notifyListeners();

    // reset error after notify
    _errorMessage = null;
    notifyListeners();
  }

  Future<void> localLogout() async {
    await _authRepository.localLogout();
    _loggedInUser = null;
    notifyListeners();
  }

  Future<void> logout() async {
    _errorMessage = null;
    notifyListeners();

    final result = await _authRepository.logout();

    switch (result) {
      case Ok<LogoutResponse>():
        localLogout();
        break;
      case Error<LogoutResponse>():
        _errorMessage = result.error.toString();
        break;
    }

    notifyListeners();

    _errorMessage = null;
    notifyListeners();
  }

  Future<void> forgotPassword(BuildContext context) async {
    _isLoadingForgot = true;
    _errorMessageForget = null;
    successMessage = null;
    notifyListeners();

    final result = await _authRepository.forgotPassword(
      email: emailController.text.trim(),
    );

    switch (result) {
      case Ok<ForgotPasswordResponseModel>():
        _isLoadingForgot = false;
        successMessage = result.value.message;
        notifyListeners();
        log('$successMessage');

        break;

      case Error<ForgotPasswordResponseModel>():
        _isLoadingForgot = false;
        _errorMessageForget = result.error.toString();
        notifyListeners();

        Future.microtask(() {
          _errorMessageForget = null;
        });
        break;
    }
  }

  void clearMessages() {
    successMessage = null;
    _errorMessage = null;
    notifyListeners();
  }

  Future<void> verifyOtp(BuildContext context) async {
    _isLoadingOtp = true;
    _errorMessageOtp = null;
    notifyListeners();

    final result = await _authRepository.verifyOtp(
      code: otpController.text.trim(),
      email: emailController.text.trim(),
    );

    switch (result) {
      case Ok<VerifyOtpResponseModel>():
        _isLoadingOtp = false;
        resetToken = result.value.data.token;
        break;

      case Error<VerifyOtpResponseModel>():
        _isLoadingOtp = false;
        _errorMessageOtp = result.error.toString();
        break;
    }

    notifyListeners();

    _errorMessageOtp = null;
    notifyListeners();
  }

  Future<void> resetPassword() async {
    _isResetPasswordLoading = true;
    _resetPasswordErrorMessage = null;
    notifyListeners();

    final result = await _authRepository.resetPassword(
      newPassword: newPasswordController.text.trim(),
      token: '',
    );
    switch (result) {
      case Ok<ResetPasswordResponse>():
        break;
      case Error<ResetPasswordResponse>():
        _resetPasswordErrorMessage = result.error.toString();
        break;
    }
    _isResetPasswordLoading = false;
    notifyListeners();
    _resetPasswordErrorMessage = null;
    notifyListeners();
  }

  @override
  void dispose() {
    usernameController.dispose();
    passwordController.dispose();
    emailController.dispose();
    newPasswordController.dispose();
    otpController.dispose();

    usernameFocus.dispose();
    passwordFocus.dispose();
    emailFocus.dispose();
    newPasswordFocus.dispose();
    otpFocus.dispose();

    super.dispose();
  }
}
