import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/utils/app_message.dart';
import 'package:flux/features/master_data/staff/data/staff_repository.dart';
import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
part 'auth_state.dart';

class AuthCubit extends Cubit<AuthState> {
  final _supabase = GetIt.instance<SupabaseClient>();
  final _staffRepository = GetIt.instance<StaffRepository>();

  AuthCubit() : super(const AuthState());

  void toggleMode() {
    emit(state.copyWith(isLoginMode: !state.isLoginMode));
  }

  Future<bool> submitAuth(String email, String password) async {
    // <-- Modificato in bool
    // Partiamo puliti: via vecchi messaggi ed errori
    emit(state.copyWith(status: AuthStatus.loading));

    try {
      if (state.isLoginMode) {
        // --- LOGICA LOGIN ---
        await _supabase.auth.signInWithPassword(
          email: email,
          password: password,
        );

        // Il login è andato a buon fine!
        emit(
          AuthState(
            status: AuthStatus.initial,
            isLoginMode: true,
            errorMessage: null,
            infoMessage: null,
          ),
        );
        return true;
      } else {
        // --- LOGICA SIGNUP ---
        final AuthResponse res = await _supabase.auth.signUp(
          email: email,
          password: password,
        );

        if (res.session == null) {
          emit(
            state.copyWith(
              status: AuthStatus.initial,
              infoMessage: AppMessage(
                key: 'authCubitCheckEmailToConfirmAccount',
              ),
            ),
          );
        } else {
          emit(state.copyWith(status: AuthStatus.initial));
          GetIt.I<SessionCubit>().initializeSession();
        }

        // Anche la registrazione è andata a buon fine!
        emit(
          AuthState(
            status: AuthStatus.initial,
            isLoginMode: true,
            errorMessage: null,
            infoMessage: null,
          ),
        );
        return true;
      }
    } on AuthException catch (e) {
      emit(state.copyWith(status: AuthStatus.failure, errorMessage: e.message));
      return false; // <-- Il login è fallito
    } catch (e) {
      emit(
        state.copyWith(
          status: AuthStatus.failure,
          errorMessage: "Errore imprevisto: $e",
        ),
      );
      return false; // <-- Il login è fallito
    }
  }

  Future<void> requestPasswordReset(String email) async {
    if (email.isEmpty) {
      emit(
        state.copyWith(
          status: AuthStatus.failure,
          errorMessage: 'Devi inserire l\'indirizzo email',
        ),
      );
      return;
    }
    await _staffRepository.resetPassword(email);
    emit(
      state.copyWith(
        status: AuthStatus.pwResetSent,
        infoMessage: AppMessage(
          key: 'authCubitResetPasswordEmailSentTo',
          argument: email,
        ),
      ),
    );
  }

  Future<void> requestLogout() async {
    await _supabase.auth.signOut();
    emit(state.copyWith(status: AuthStatus.initial));
  }
}
