import 'dart:convert';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/user.dart';
import 'api_service.dart';

class AuthService extends GetxController {
  static AuthService get to => Get.find();
  
  final _isAuthenticated = false.obs;
  final _isLoading = true.obs;
  final _currentUser = Rxn<User>();
  final _token = Rxn<String>();
  final _apiService = ApiService();

  RxBool get isAuthenticated => _isAuthenticated;
  RxBool get isLoading => _isLoading;
  Rxn<User> get currentUser => _currentUser;
  Rxn<String> get token => _token;

  @override
  void onInit() {
    super.onInit();
    _loadStoredAuth();
  }

  Future<void> _loadStoredAuth() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final storedToken = prefs.getString('auth_token');
      final storedUser = prefs.getString('user_data');

      print('Stored token: ${storedToken != null ? 'exists' : 'null'}');
      print('Stored user: ${storedUser != null ? 'exists' : 'null'}');

      if (storedToken != null && storedUser != null) {
        _token.value = storedToken;
        try {
          // Parse the stored user data properly - it's stored as a JSON string
          final userMap = jsonDecode(storedUser) as Map<String, dynamic>;
          print('Parsed user data: $userMap');
          _currentUser.value = User.fromJson(userMap);
          _isAuthenticated.value = true;
          print('Successfully loaded stored auth data');
        } catch (e) {
          print('Error parsing stored user data: $e');
          print('Raw stored user data: $storedUser');
          // Clear corrupted data
          final prefs = await SharedPreferences.getInstance();
          await prefs.remove('user_data');
          await prefs.remove('auth_token');
          print('Cleared corrupted auth data');
        }
      } else {
        print('No stored auth data found');
      }
    } catch (e) {
      print('Error loading stored auth: $e');
    } finally {
      _isLoading.value = false;
    }
  }

  Future<bool> login(String mobileNumber, String password) async {
    try {
      _isLoading.value = true;
      
      final response = await _apiService.login(mobileNumber, password);
      
      if (response['success']) {
        final userData = response['data']['user'];
        final token = response['data']['token'];
        
        final user = User(
          id: userData['id'],
          mobileNumber: userData['mobile_number'],
          fullName: userData['full_name'],
          role: userData['role'],
          isActive: userData['is_active'] ?? true,
          createdAt: DateTime.parse(userData['created_at']),
          updatedAt: DateTime.parse(userData['updated_at']),
        );
        
        await _saveAuthData(token, user);
        
        _token.value = token;
        _currentUser.value = user;
        _isAuthenticated.value = true;
        
        return true;
      } else {
        Get.snackbar('Login Failed', response['message']);
        return false;
      }
    } catch (e) {
      print('Login error: $e');
      Get.snackbar('Error', 'Login failed. Please try again.');
      return false;
    } finally {
      _isLoading.value = false;
    }
  }

  Future<void> _saveAuthData(String token, User user) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('auth_token', token);
    await prefs.setString('user_data', jsonEncode(user.toJson()));
  }

  Future<void> logout() async {
    try {
      await _apiService.logout();
      
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('auth_token');
      await prefs.remove('user_data');
      
      _token.value = null;
      _currentUser.value = null;
      _isAuthenticated.value = false;
    } catch (e) {
      print('Logout error: $e');
    }
  }

  Future<bool> changePassword(String currentPassword, String newPassword) async {
    try {
      _isLoading.value = true;
      
      final response = await _apiService.changePassword(currentPassword, newPassword);
      
      if (response['success']) {
        Get.snackbar('Success', 'Password changed successfully');
        return true;
      } else {
        Get.snackbar('Failed', response['message']);
        return false;
      }
    } catch (e) {
      print('Change password error: $e');
      Get.snackbar('Error', 'Failed to change password');
      return false;
    } finally {
      _isLoading.value = false;
    }
  }
}
