import 'package:flutter/material.dart';
import '../models/pet_model.dart';
import '../services/api_service.dart';
import '../services/auth_service.dart';

class PetProvider with ChangeNotifier {
  final ApiService _apiService = ApiService();
  final AuthService _authService = AuthService();

  List<Pet> _pets = [];
  Pet? _selectedPet;
  bool _isLoading = false;
  int? _userId;

  List<Pet> get pets => _pets;
  Pet? get selectedPet => _selectedPet;
  bool get isLoading => _isLoading;
  int? get userId => _userId;

  // Load user and then pets
  Future<void> loadUserAndPets() async {
    _isLoading = true;
    // notifyListeners(); // Avoid notifying during build if called from init

    try {
      final userInfo = await _authService.getUserInfo();
      if (userInfo != null) {
        _userId = userInfo['id'] is int
            ? userInfo['id']
            : int.tryParse(userInfo['id'].toString());

        if (_userId != null) {
          await _fetchPets();
        }
      }
    } catch (e) {
      debugPrint('Error loading user/pets in provider: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // Fetch pets from API
  Future<void> _fetchPets() async {
    if (_userId == null) return;
    try {
      final petsData = await _apiService.getPets(_userId!);
      _pets = petsData.map((e) => Pet.fromMap(e)).toList();

      // Set default selected pet if needed
      if (_pets.isNotEmpty) {
        if (_selectedPet == null) {
          _selectedPet = _pets.first;
        } else {
          // Verify if currently selected pet still exists (e.g. after update)
          final exists = _pets.any((p) => p.id == _selectedPet!.id);
          if (exists) {
            // Update the object to get latest data
            _selectedPet = _pets.firstWhere((p) => p.id == _selectedPet!.id);
          } else {
            _selectedPet = _pets.first;
          }
        }
      } else {
        _selectedPet = null;
      }
    } catch (e) {
      debugPrint('Error fetching pets: $e');
      _pets = [];
    }
  }

  // Refresh data (e.g. after add/edit)
  Future<void> refreshPets() async {
    await _fetchPets();
    notifyListeners();
  }

  // Select a pet
  void selectPet(Pet pet) {
    _selectedPet = pet;
    notifyListeners();
  }

  // Clear state (e.g. on logout)
  void clearState() {
    _userId = null;
    _pets = [];
    _selectedPet = null;
    notifyListeners();
  }
}
