import 'package:flutter/material.dart';
import 'package:gen_service/Models/ProfileDataResponse.dart';
import 'package:gen_service/Services/api_calling.dart';

import '../Models/DashboardResponse.dart';

class DashboardProvider extends ChangeNotifier {
  /// Dashboard data
  DashboardResponse? _dashboardData;

  /// Loading state
  bool _isLoading = false;

  /// Error message (if any)
  String? _errorMessage;

  // =======================
  // Getters
  // =======================
  DashboardResponse? get dashboardData => _dashboardData;
  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;

  // =======================
  // Fetch Dashboard API
  // =======================
  Future<void> fetchDashboard(String accId, String sessionId) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await ApiCalling.fetchDashboardApi(accId, sessionId);

      if (response != null) {
        if (response.error == "0") {
          _dashboardData = response;
        } else {
          _errorMessage = response.message ?? "Something went wrong!";
        }
      } else {
        _errorMessage = "No response from server.";
      }
    } catch (e) {
      _errorMessage = "Failed to fetch dashboard: $e";
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }


  // Fetch Profile provider
  // =======================
  ProfileDataResponse? _profileData;
  ProfileDataResponse? get profileData => _profileData;
  Future<void> fetchProfile(String accId, String sessionId) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await ApiCalling.fetchProfileDataApi(accId, sessionId);

      if (response != null) {
        if (response.error?.toString() == "0") {
          _profileData = response;
        } else {
          _errorMessage = response.message ?? "Something went wrong!";
        }
      } else {
        _errorMessage = "No response from server.";
      }
    } catch (e) {
      debugPrint("❌ fetchProfile error: $e");
      _errorMessage = "Failed to fetch profile data: ${e.toString()}";
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }


  // =======================
  // Refresh Dashboard
  // =======================
  Future<void> refreshDashboard(String accId, String sessionId) async {
    await fetchDashboard(accId, sessionId);
  }

  // =======================
  // Clear Data
  // =======================
  void clear() {
    _dashboardData = null;
    _errorMessage = null;
    _isLoading = false;
    notifyListeners();
  }


}
