import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:medora/data/models/consultation_booking.dart';

class BookingService {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  Future<String> createBooking({
    required String doctorId,
    required String profileImageUrl,
    required String doctorName,
    required String patientId,
    required String patientName,
    required String location,
    required DateTime appointmentDate,
    required String appointmentTime,
    required int consultationFee,
    required String specialization,
  }) async {
    try {
      final docRef = _firestore.collection('bookings').doc();

      final booking = Booking(
        id: docRef.id,
        doctorId: doctorId,
        doctorName: doctorName,
        patientId: patientId,
        patientName: patientName,
        location: location,
        appointmentDate: appointmentDate,
        appointmentTime: appointmentTime,
        consultationFee: consultationFee,
        paymentStatus: PaymentStatus.pending,
        createdAt: DateTime.now(),
        specialization: specialization,
        profileImageUrl: profileImageUrl,
      );

      docRef.set(booking.toMap());
      return docRef.id;
    } catch (e) {
      throw Exception('Failed to create booking: $e');
    }
  }

  Future<Booking> getBooking(String bookingId) async {
    try {
      final doc = await _firestore.collection('bookings').doc(bookingId).get();
      if (!doc.exists) {
        throw Exception('Booking not found');
      }
      return Booking.fromMap(doc.data()!);
    } catch (e) {
      throw Exception('Failed to get booking: $e');
    }
  }

  Stream<List<Booking>> getPatientBookings(String patientId) {
    return _firestore
        .collection('bookings')
        .where('patientId', isEqualTo: patientId)
        .orderBy('appointmentDate', descending: true)
        .snapshots()
        .map((snapshot) =>
            snapshot.docs.map((doc) => Booking.fromMap(doc.data())).toList());
  }

  Stream<List<Booking>> getDoctorBookings(String doctorId) {
    return _firestore
        .collection('bookings')
        .where('doctorId', isEqualTo: doctorId)
        .orderBy('appointmentDate', descending: true)
        .snapshots()
        .map((snapshot) =>
            snapshot.docs.map((doc) => Booking.fromMap(doc.data())).toList());
  }

  Future<void> updatePaymentStatus(
    String bookingId,
    PaymentStatus status,
  ) async {
    try {
      await _firestore.collection('bookings').doc(bookingId).update({
        'paymentStatus': status.toString().split('.').last,
      });
    } catch (e) {
      throw Exception('Failed to update payment status: $e');
    }
  }
}
