import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:prosappco/src/models/user_model.dart';

class ScoresModel {
  late int total;
  late double average;
  final List<ScoreDetailModel> details;

  ScoresModel(this.details) {
    total = details.length;
    average = averageScore(details);
  }

  @override
  String toString() {
    return 'ScoresModel{total: $total, average: $average, details: $details}';
  }

  double averageScore(List<ScoreDetailModel> details) {
    if (details.isEmpty) {
      return 0.0;
    }
    final sum = details.map((detail) => detail.score).reduce((a, b) => a + b);
    return sum / details.length;
  }

  // Me
  static Future<ScoresModel> scoreTo(
      String userReceived, bool isFromClient, bool userInfo) async {
    final receivedScoresQuery = FirebaseFirestore.instance
        .collection('scores')
        .where('is_from_professional', isEqualTo: isFromClient)
        .where('to_user', isEqualTo: userReceived);

    final receivedScoresSnapshot = await receivedScoresQuery.get();

    final receivedScores = await Future.wait(receivedScoresSnapshot.docs
        .map((doc) async =>
            await ScoreDetailModel.fromDocumentSnapshot(doc, userInfo))
        .toList());

    return ScoresModel(receivedScores);
  }

  // You
  static Future<ScoresModel> scoreFrom(
      String userGiven, bool isFromClient, bool userInfo) async {
    final givenScoresQuery = FirebaseFirestore.instance
        .collection('scores')
        .where('is_from_professional', isEqualTo: isFromClient)
        .where('from_user', isEqualTo: userGiven);

    final givenScoresSnapshot = await givenScoresQuery.get();

    final givenScores = await Future.wait(givenScoresSnapshot.docs
        .map((doc) async =>
            await ScoreDetailModel.fromDocumentSnapshot(doc, userInfo))
        .toList());

    return ScoresModel(givenScores);
  }
}

class ScoreDetailModel {
  final String id;
  final double score;
  final String fromUser;
  final String toUser;
  final String comment;
  final bool isFromClient;

  final String name;
  final Reference? avatar;

  ScoreDetailModel({
    required this.id,
    required this.score,
    required this.fromUser,
    required this.toUser,
    required this.comment,
    required this.isFromClient,
    required this.name,
    required this.avatar,
  });

  @override
  String toString() {
    return 'ScoreDetailModel{id: $id, score: $score, fromUser: $fromUser, toUser: $toUser, comment: $comment, isFromClient: $isFromClient, name: $name, avatar: $avatar}';
  }

  static Future<ScoreDetailModel> fromDocumentSnapshot(
      DocumentSnapshot<Map<String, dynamic>> snapshot, bool userInfo) async {
    try {
      final Map<String, dynamic> data = snapshot.data()!;
      final user = userInfo ? await UserModel.getUser(data['from_user']) : null;

      return ScoreDetailModel(
          id: snapshot.id,
          score: double.parse(data['score'].toString()),
          fromUser: data['from_user'],
          toUser: data['to_user'],
          comment: data['comment'],
          isFromClient: data['is_from_professional'],
          name: user?.name ?? "...",
          avatar: user?.photo);
    } catch (e) {
      print('error en score $e');
      rethrow;
    }
  }
}
