import 'dart:convert';

import 'package:apps_sidang/common/helper/constant.dart';
import 'package:apps_sidang/src/prediction/model/predict_model.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:logger/logger.dart';

class PredictProvider extends ChangeNotifier {
  bool _withLoading = false;
  Logger logger = Logger();
  PredictModel _predictModel = PredictModel();

  bool get withLoading => _withLoading;
  PredictModel get predictModel => _predictModel;

  void isLoading(bool value) {
    _withLoading = value;
    notifyListeners();
  }

  Future<void> fetchPredict({
    required double height,
    required String age,
    required String gender,
    required String breastfeeding,
  }) async {
    isLoading(true);
    notifyListeners();

    try {
      final response = await http.get(
        Uri.parse('${Constant.BASE_URL}/predict').replace(
          queryParameters: {
            'height': height.toString(),
            'age': age,
            'gender': gender,
            'breastfeeding': breastfeeding,
          },
        ),
      );
      if (response.statusCode == 200) {
        _predictModel = PredictModel.fromJson(jsonDecode(response.body));
        logger.d(response.body);
        isLoading(false);
        notifyListeners();
      } else {
        _predictModel = PredictModel.fromJson(jsonDecode(response.body));
        logger.e('Failed to load data. Status code: ${response.statusCode}');
        isLoading(false);
        notifyListeners();
      }
    } catch (e) {
      logger.e('Error: $e');
      isLoading(false);
      notifyListeners();
    }
  }
}
