import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class ApiService {
  // Ganti localhost ke IP PC Anda jika running di emulator/HP asli
  static const String baseUrl = 'https://ta.myhost.id/E31230906/api';
 

  static const String loginEndpoint          = '/teknisi/login';
  static const String logoutEndpoint         = '/teknisi/logout';
  static const String meEndpoint             = '/teknisi/me';
  static const String refreshEndpoint        = '/teknisi/refresh';
  static const String changePasswordEndpoint = '/teknisi/change-password';
  static const String dashboardEndpoint      = '/dashboard';
  static const String gajiRiwayatEndpoint    = '/gaji/riwayat';
  static const String kasbonRiwayatEndpoint  = '/kasbon/riwayat';

  static const Duration timeoutDuration = Duration(seconds: 30);

  // ===================================
  // TOKEN
  // ===================================

  Future<String?> getToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      return prefs.getString('access_token');
    } catch (e) {
      print('Error getting token: $e');
      return null;
    }
  }

  Future<void> saveToken(String token) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('access_token', token);
      await prefs.setString('auth_token', token); 
    } catch (e) {
      print('Error saving token: $e');
    }
  }

  Future<void> removeToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('access_token');
      await prefs.remove('auth_token'); 
    } catch (e) {
      print('Error removing token: $e');
    }
  }

  // ===================================
  // USER DATA
  // ===================================

  Future<void> saveUserData(Map<String, dynamic> userData) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('user_data', jsonEncode(userData));

      final teknisi = userData['teknisi'];
      if (teknisi != null && teknisi['id_teknisi'] != null) {
        await prefs.setInt('id_teknisi', teknisi['id_teknisi']);
      }
    } catch (e) {
      print('Error saving user data: $e');
    }
  }

  Future<Map<String, dynamic>?> getUserData() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final userDataString = prefs.getString('user_data');
      if (userDataString != null) {
        return jsonDecode(userDataString);
      }
      return null;
    } catch (e) {
      print('Error getting user data: $e');
      return null;
    }
  }

  Future<void> removeUserData() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('user_data');
      await prefs.remove('auth_token');  
      await prefs.remove('id_teknisi'); 
    } catch (e) {
      print('Error removing user data: $e');
    }
  }

  // ===================================
  // AUTH CHECK
  // ===================================

  Future<bool> isLoggedIn() async {
    final token = await getToken();
    return token != null && token.isNotEmpty;
  }

  // ===================================
  // LOGIN
  // ===================================

  Future<Map<String, dynamic>> login(String username, String password) async {
    try {
      final response = await http.post(
        Uri.parse('$baseUrl$loginEndpoint'),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: jsonEncode({
          'username': username,
          'password': password,
        }),
      ).timeout(timeoutDuration);

      final data = jsonDecode(response.body);

      if (response.statusCode == 200 && data['success'] == true) {
        if (data['access_token'] != null) {
          await saveToken(data['access_token']);
        }
        if (data['user'] != null) {
          await saveUserData(data['user']);
        }
        return {
          'success': true,
          'message': data['message'] ?? 'Login berhasil',
          'data': data,
        };
      } else {
        return {
          'success': false,
          'message': data['message'] ?? 'Login gagal',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': 'Terjadi kesalahan: ${e.toString()}',
      };
    }
  }

  // ===================================
  // LOGOUT
  // ===================================

  Future<Map<String, dynamic>> logout() async {
    try {
      final token = await getToken();
      if (token != null) {
        await http.post(
          Uri.parse('$baseUrl$logoutEndpoint'),
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': 'Bearer $token',
          },
        ).timeout(timeoutDuration);
      }
      await removeToken();
      await removeUserData();
      return {'success': true, 'message': 'Logout berhasil'};
    } catch (e) {
      await removeToken();
      await removeUserData();
      return {'success': true, 'message': 'Logout berhasil'};
    }
  }

  // ===================================
  // GET PROFILE
  // ===================================

  Future<Map<String, dynamic>> getProfile() async {
    try {
      final token = await getToken();
      if (token == null) return {'success': false, 'message': 'Token tidak ditemukan', 'logout': true};
      final response = await http.get(
        Uri.parse('$baseUrl$meEndpoint'),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        },
      ).timeout(timeoutDuration);
      final data = jsonDecode(response.body);
      if (response.statusCode == 200 && data['success'] == true) {
        if (data['data'] != null) await saveUserData(data['data']);
        return {'success': true, 'message': data['message'] ?? 'Data berhasil diambil', 'data': data['data']};
      } else if (response.statusCode == 401) {
        await removeToken();
        await removeUserData();
        return {'success': false, 'message': 'Sesi expired', 'logout': true};
      }
      return {'success': false, 'message': 'Gagal mengambil data'};
    } catch (e) {
      return {'success': false, 'message': e.toString()};
    }
  }

  // ===================================
  // CHANGE PASSWORD
  // ===================================

  Future<Map<String, dynamic>> changePassword({
    required String oldPassword,
    required String newPassword,
    required String confirmPassword,
  }) async {
    try {
      final token = await getToken();
      if (token == null) return {'success': false, 'message': 'Auth error'};
      final response = await http.post(
        Uri.parse('$baseUrl$changePasswordEndpoint'),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        },
        body: jsonEncode({
          'password_lama': oldPassword,
          'password_baru': newPassword,
          'password_baru_confirmation': confirmPassword,
        }),
      ).timeout(timeoutDuration);
      final data = jsonDecode(response.body);
      return {'success': data['success'] ?? false, 'message': data['message'] ?? 'Gagal'};
    } catch (e) {
      return {'success': false, 'message': e.toString()};
    }
  }

  // ===================================
  // DASHBOARD & FINANCE
  // ===================================

  Future<Map<String, dynamic>> getDashboardData() async {
    try {
      final token = await getToken();
      final prefs = await SharedPreferences.getInstance();
      final idTeknisi = prefs.getInt('id_teknisi');
      if (token == null || idTeknisi == null) return {'success': false, 'message': 'Auth error'};
      final response = await http.get(
        Uri.parse('$baseUrl$dashboardEndpoint?id_teknisi=$idTeknisi'),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        },
      ).timeout(timeoutDuration);
      return jsonDecode(response.body);
    } catch (e) { return {'success': false, 'message': e.toString()}; }
  }

  Future<Map<String, dynamic>> getGajiRiwayat() async {
    try {
      final token = await getToken();
      final prefs = await SharedPreferences.getInstance();
      final idTeknisi = prefs.getInt('id_teknisi');
      
      // Pastikan endpoint benar: /gaji/riwayat?id_teknisi=...
      final url = Uri.parse('$baseUrl$gajiRiwayatEndpoint?id_teknisi=$idTeknisi');
      print('Fetching Gaji from: $url'); // Debug info

      final response = await http.get(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        },
      ).timeout(timeoutDuration);
      
      return jsonDecode(response.body);
    } catch (e) { 
      print('Error Gaji API: $e');
      return {'success': false, 'message': e.toString()}; 
    }
  }

  Future<Map<String, dynamic>> getGajiDetail(int id) async {
    try {
      final token = await getToken();
      final prefs = await SharedPreferences.getInstance();
      final idTeknisi = prefs.getInt('id_teknisi');
      final response = await http.get(
        Uri.parse('$baseUrl/gaji/$id?id_teknisi=$idTeknisi'),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        },
      ).timeout(timeoutDuration);
      return jsonDecode(response.body);
    } catch (e) { return {'success': false, 'message': e.toString()}; }
  }

  Future<Map<String, dynamic>> getKasbonRiwayat() async {
    try {
      final token = await getToken();
      final prefs = await SharedPreferences.getInstance();
      final idTeknisi = prefs.getInt('id_teknisi');
      final response = await http.get(
        Uri.parse('$baseUrl$kasbonRiwayatEndpoint?id_teknisi=$idTeknisi'),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        },
      ).timeout(timeoutDuration);
      return jsonDecode(response.body);
    } catch (e) { return {'success': false, 'message': e.toString()}; }
  }
}