import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:medora/controllers/consultation_center_controller.dart';
import 'package:medora/data/models/consultation_center.dart';

class ConsultationCenterService {
  static final String consultationCenterCollectionName =
      dotenv.env['CONSULTATION_CENTER_COLLECTION_NAME']!;
  static final FirebaseFirestore db = FirebaseFirestore.instance;

  // Get List of Consultation Centers for a Doctor
  static Future<List<ConsultationCenter>> getDoctorConsultationCenters(
      String doctorUid) async {
    try {
      if (doctorUid.isEmpty) {
        print('Doctor UID is empty');
        return [];
      }

      final QuerySnapshot querySnapshot = await db
          .collection(consultationCenterCollectionName)
          .where('uid', isEqualTo: doctorUid)
          .get();

      final List<ConsultationCenter> consultationCenters =
          querySnapshot.docs.map((doc) {
        Map<String, dynamic> data = doc.data() as Map<String, dynamic>;
        data['documentId'] = doc.id;
        return ConsultationCenter.fromJson(data);
      }).toList();

      return consultationCenters;
    } catch (e) {
      print('Error fetching doctor consultation centers: $e');
      return [];
    }
  }

  // Save Multiple Consultation Centers
  static Future<bool> saveConsultationCenters(
      List<ConsultationCenterController> controllers) async {
    try {
      final User? user = FirebaseAuth.instance.currentUser;
      if (user == null) {
        print('No user logged in');
        return false;
      }

      final String uid = user.uid;
      final WriteBatch batch = db.batch();

      for (var controller in controllers) {
        final ConsultationCenter consultationData = controller.model;
        final Map<String, dynamic> consultationJson = consultationData.toJson();

        // Add timestamps and user ID
        consultationJson['createdAt'] = FieldValue.serverTimestamp();
        consultationJson['updatedAt'] = FieldValue.serverTimestamp();
        consultationJson['uid'] = uid;

        // Create a new document reference
        final DocumentReference docRef = db
            .collection(consultationCenterCollectionName)
            .doc(); // Auto-generated ID

        // Add to batch
        batch.set(docRef, consultationJson);
      }

      // Commit the batch
      await batch.commit();
      print('Consultation centers saved successfully');
      return true;
    } catch (e) {
      print('Error saving consultation centers: $e');
      return false;
    }
  }

  // Update Multiple Consultation Centers
  static Future<bool> updateConsultationCenters(
      List<ConsultationCenterController> controllers) async {
    try {
      final User? user = FirebaseAuth.instance.currentUser;
      if (user == null) {
        print('No user logged in');
        return false;
      }

      final WriteBatch batch = db.batch();

      for (var controller in controllers) {
        final ConsultationCenter consultationData = controller.model;
        final Map<String, dynamic> consultationJson = consultationData.toJson();

        // Add updated timestamp
        consultationJson['updatedAt'] = FieldValue.serverTimestamp();

        // Assuming each consultation center has a unique document ID
        final DocumentReference docRef = db
            .collection(consultationCenterCollectionName)
            .doc(consultationData
                .documentId); // You'll need to add documentId to the model

        // Add to batch
        batch.update(docRef, consultationJson);
      }

      // Commit the batch
      await batch.commit();
      print('Consultation centers updated successfully');
      return true;
    } catch (e) {
      print('Error updating consultation centers: $e');
      return false;
    }
  }

  // Delete a Specific Consultation Center
  static Future<bool> deleteConsultationCenter({
    required String doctorUid,
    required String documentId,
  }) async {
    try {
      if (doctorUid.isEmpty || documentId.isEmpty) {
        print('Doctor UID or Document ID is empty');
        return false;
      }

      // First verify that this center belongs to the doctor
      final DocumentSnapshot doc = await db
          .collection(consultationCenterCollectionName)
          .doc(documentId)
          .get();

      if (!doc.exists) {
        print('Consultation center not found');
        return false;
      }

      final data = doc.data() as Map<String, dynamic>;
      if (data['doctorUid'] != doctorUid) {
        print('Consultation center does not belong to this doctor');
        return false;
      }

      await db
          .collection(consultationCenterCollectionName)
          .doc(documentId)
          .delete();

      print('Consultation center deleted successfully');
      return true;
    } catch (e) {
      print('Error deleting consultation center: $e');
      return false;
    }
  }
}
