import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:prosappco/src/authentication/authentication_repository.dart';
import 'package:prosappco/src/models/scores_model.dart';

final uid = AuthenticationRepository.instance.getCurrentUserUid();

class EventoService {
  Future<String?> createEvent(
    String title,
    String description,
    String day,
    String range1Hour1,
    String range1Hour2,
    String professionalId,
    String ubicacion,
    String address,
    double latitude,
    double longitude,
    String status,
    int? tarifa,
    bool professionalScored,
    bool userScored,
  ) async {
    try {
      DateTime ahora = DateTime.now();

      final eventId =
          await FirebaseFirestore.instance.collection('services').add({
        'user_id': uid,
        'title': title,
        'description': description,
        'day': day,
        'range1Hour1': range1Hour1,
        'range1Hour2': range1Hour2,
        'professional_id': professionalId,
        'ubicacion': ubicacion,
        'address': address,
        'latitude': latitude,
        'longitude': longitude,
        'status': status,
        'Timestamp': ahora,
        'tarifa': tarifa ?? 0,
        'professional_scored': professionalScored,
        'user_scored': userScored,
      }).then((value) {
        FirebaseFirestore.instance.collection('users').doc(uid).update({
          'services': FieldValue.arrayUnion([value.id])
        });

        return value.id;
      });

      return eventId;
    } catch (e) {
      print('Evento $e');
    }
    return null;
  }
}

Future<List<Event>> getByProId(String day) async {
  try {
    var snapshot = await FirebaseFirestore.instance
        .collection('services')
        .where('professional_id', isEqualTo: uid)
        .where('day', isEqualTo: day.toString())
        .where('status', isEqualTo: 'aprobado')
        .get();

    List<Event> eventos = [];
    for (var element in snapshot.docs) {
      final event = Event.fromJson(element.data());
      event.scoresModel = await ScoresModel.scoreTo(event.userId, false, false);
      event.id = element.id;
      eventos.add(event);
    }
    return eventos;
  } catch (e) {
    print('Error getByProId $e');
    return [];
  }
}

Future<List<Event>> getByProIdAll(String state1, String state2) async {
  try {
    var snapshot = await FirebaseFirestore.instance
        .collection('services')
        .where('professional_id', isEqualTo: uid)
        .where('status', whereIn: [state1, state2]).get();

    List<Event> eventos = [];
    for (var element in snapshot.docs) {
      final event = Event.fromJson(element.data());
      event.scoresModel = await ScoresModel.scoreTo(event.userId, false, false);
      event.id = element.id;
      eventos.add(event);
    }
    return eventos;
  } catch (e) {
    print('Error getByProId $e');
    return [];
  }
}

Future<List<Event>> getByUserIdAll(String state1, String state2) async {
  try {
    var snapshot = await FirebaseFirestore.instance
        .collection('services')
        .where('user_id', isEqualTo: uid)
        .where('status', whereIn: [state1, state2]).get();

    List<Event> eventos = [];
    for (var element in snapshot.docs) {
      final event = Event.fromJson(element.data());
      event.scoresModel = await ScoresModel.scoreTo(event.userId, false, false);
      event.id = element.id;
      eventos.add(event);
    }
    return eventos;
  } catch (e) {
    print('Error getByUserId $e');
    return [];
  }
}

class Event {
  String? id;
  String title;
  String? description;
  String day;
  String range1Hour1;
  String? range1Hour2;
  String userId;
  String professionalId;
  String? ubicacion;
  String? address;
  double? longitud;
  double? latitud;
  String status;
  ScoresModel? scoresModel;
  int? tarifa;
  bool professionalScored;
  bool userScored;

  Event({
    this.id,
    required this.title,
    this.description,
    required this.day,
    required this.range1Hour1,
    this.range1Hour2,
    required this.userId,
    required this.professionalId,
    this.ubicacion,
    this.address,
    this.longitud,
    this.latitud,
    this.status = 'pendiente',
    this.tarifa,
    this.professionalScored = false,
    this.userScored = false,
  });

  factory Event.fromJson(Map<String, dynamic> json) {
    return Event(
      id: json['id'] ?? '',
      title: json['title'],
      description: json['description'],
      day: json['day'],
      range1Hour1: json['range1Hour1'],
      range1Hour2: json['range1Hour2'],
      userId: json['user_id'],
      professionalId: json['professional_id'],
      ubicacion: json['ubicacion'] ?? '',
      address: json['address'] ?? '',
      longitud: json['longitude'] ?? 0,
      latitud: json['latitude'] ?? 0,
      status: json['status'],
      tarifa: json['tarifa'] ?? 0,
      professionalScored: json['professional_scored'],
      userScored: json['user_scored'],
    );
  }

  static Future<Event> getEventById(String uid) async {
    try {
      final snapshot = await FirebaseFirestore.instance
          .collection('services')
          .doc(uid)
          .get();
      final Map<String, dynamic>? data = snapshot.data();
      return Event.fromJson(data!);
    } catch (e) {
      print('Error getting user: $e');
      return Event(
          title: '', day: '', range1Hour1: '', userId: '', professionalId: '');
    }
  }

  static Future<List<Event>> getEventsAllById(String uid) async {
    try {
      var snapshot = await FirebaseFirestore.instance
          .collection('services')
          .where('professional_id', isEqualTo: uid)
          .get();

      List<Event> eventos = [];
      for (var element in snapshot.docs) {
        eventos.add(Event.fromJson(element.data()));
      }
      return eventos;
    } catch (e) {
      print('Error getByProId $e');
      return [];
    }
  }

  static Future<List<Event>> getEventsAllByIdStatus(
      String uid, String state) async {
    try {
      var snapshot = await FirebaseFirestore.instance
          .collection('services')
          .where('professional_id', isEqualTo: uid)
          .where('status', isEqualTo: state)
          .get();

      List<Event> eventos = [];
      for (var element in snapshot.docs) {
        eventos.add(Event.fromJson(element.data()));
      }
      return eventos;
    } catch (e) {
      print('Error getByProId $e');
      return [];
    }
  }
}
