import 'package:jwt_decoder/jwt_decoder.dart';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:chepuhagram/core/constants.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class ApiService extends ChangeNotifier {
  final _client = http.Client();
  final _storage = const FlutterSecureStorage();
  

  Future<bool> refreshToken() async {
    notifyListeners();

    try {
      final refreshToken = await _storage.read(key: 'refresh_token');
      final response = await _client.post(
        Uri.http(AppConstants.baseUrl, 'auth/refresh'),
        body: jsonEncode({'refresh_token': refreshToken}),
        headers: {'Content-Type': 'application/json'},
      );

      final decodedResponse =
          jsonDecode(utf8.decode(response.bodyBytes)) as Map;

      if (response.statusCode == 200) {
        await _storage.write(
          key: 'access_token',
          value: decodedResponse['access_token'],
        );
        await _storage.write(
          key: 'refresh_token',
          value: decodedResponse['refresh_token'],
        );
        notifyListeners();
        return true;
      } else {
        notifyListeners();
        return false;
      }
    } catch (e) {
      notifyListeners();
      rethrow;
    }
  }

  Future<String?> getAccessToken() async {
    String? token = await _storage.read(key: 'access_token');

    if (token != null) {
      bool isExpiredSoon = JwtDecoder.isExpired(token) ||
          JwtDecoder.getRemainingTime(token).inMinutes < 2;

      if (isExpiredSoon) {
        bool refreshed = await refreshToken();
        if (refreshed) {
          token = await _storage.read(key: 'access_token');
        } else {
          return null;
        }
      }
    }
    return token;
  }
}