import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/pro_state.dart';
import 'package:prosapp_web_app/models/service.dart';
import 'package:prosapp_web_app/models/servicio_profesional.dart';
import 'package:prosapp_web_app/models/usuario.dart';
import 'package:prosapp_web_app/services/api_service.dart';

class CalendarServicesProvider extends ChangeNotifier {
  List<ServicioProfesional> services = [];
  ServicioProfesional? service;
  bool isLoading = true;
  final _api = ApiService.instance;

  void logout() {
    services = [];
    service = null;
    isLoading = false;
    notifyListeners();
  }

  getServicesForProfessional(String userId) async {
    try {
      isLoading = true;
      final res = await _api.get('/services/professional/calendar');
      final data = (res is Map ? res['data'] : res) as List;

      // Fetch users for calendar entries (calendar endpoint returns flat list without embedded users)
      final servicios = data.map((e) {
        final m = e as Map<String, dynamic>;
        return Service.fromJson(m, m['id'] as String);
      }).toList();

      final ids = servicios.map((s) => s.userId).toSet().toList();
      final users = await Future.wait(ids.map((id) async {
        final u = await _api.get('/users/$id');
        return Usuario.fromDocument(u as Map<String, dynamic>);
      }));
      final usersMap = {for (var u in users) u.id: u};

      services = servicios
          .map((s) => ServicioProfesional(
              user: usersMap[s.userId] ?? Usuario(id: s.userId, email: null, phone: null, name: '?',
                  nickname: null, city: null, picture: null, birthday: null, gender: null,
                  proState: ProState.inactive, token: null),
              service: s))
          .toList()
        ..sort((a, b) {
          final dateA = DateTime.parse(a.service.day);
          final dateB = DateTime.parse(b.service.day);
          if (dateA != dateB) return dateA.compareTo(dateB);
          final tA = a.service.range1Hour1.hour * 60 + a.service.range1Hour1.minute;
          final tB = b.service.range1Hour1.hour * 60 + b.service.range1Hour1.minute;
          return tA.compareTo(tB);
        });
    } catch (e) {
      print('Error obteniendo servicios: $e');
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }
}
