import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:marco/helpers/services/storage/local_storage.dart';

class AuthService {
  static bool isLoggedIn = false;

  static Future<Map<String, String>?> loginUser(Map<String, dynamic> data) async {
    try {
      final response = await http.post(
        Uri.parse('https://api.marcoaiot.com/api/auth/login'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode(data),
      );

      if (response.statusCode == 200) {
        isLoggedIn = true;

        // Parse the response to get the JWT and refresh tokens
        final responseData = jsonDecode(response.body);
        
        // Adjusted for the actual response structure
        final jwtToken = responseData['data']['token']; // Ensure this matches your actual response

        // Save the JWT token in local storage
        await LocalStorage.setJwtToken(jwtToken);
        print("JWT Token: $jwtToken");

        // Optionally save refresh token if available
        final refreshToken = responseData['data']['refreshToken'];
        if (refreshToken != null) {
          await LocalStorage.setRefreshToken(refreshToken);
          print("Refresh Token: $refreshToken");
        }

        // Save the login state in local storage
        await LocalStorage.setLoggedInUser(true);

        // Return null to indicate success
        return null;
      } else if (response.statusCode == 401) {
        return {"password": "Invalid email or password"};
      } else {
        return {"error": "Something went wrong. Please try again."};
      }
    } catch (e) {
      return {"error": "Network error. Please check your connection."};
    }
  }
}
