import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:medora/controllers/doctor_controller.dart';
import 'package:medora/data/models/doctor.dart';
import 'package:path/path.dart' as path;

class DoctorProfileService {
  static final String doctorProfileCollectionName =
      dotenv.env['DOCTOR_PROFILE_COLLECTION_NAME']!;
  static final FirebaseFirestore db = FirebaseFirestore.instance;
  static final FirebaseStorage storage = FirebaseStorage.instanceFor(
      bucket: dotenv.env['FIREBASE_STORAGE_BUCKET']!);

  static Future<String?> uploadProfileImage(File imageFile) async {
    try {
      final User? user = FirebaseAuth.instance.currentUser;
      if (user == null) {
        print('No user logged in');
        return null;
      }
      final String uid = user.uid;
      final String fileName =
          'doctor_profile_${uid}_${DateTime.now().millisecondsSinceEpoch}${path.extension(imageFile.path)}';
      final Reference storageRef =
          storage.ref().child('doctor_profile_images/$fileName');

      final UploadTask uploadTask = storageRef.putFile(
        imageFile,
        SettableMetadata(
          contentType: 'image/${path.extension(imageFile.path).substring(1)}',
          customMetadata: {
            'userId': uid,
            'userType': 'doctor',
            'uploadedAt': DateTime.now().toIso8601String(),
          },
        ),
      );

      final TaskSnapshot snapshot = await uploadTask;
      final String downloadUrl = await snapshot.ref.getDownloadURL();

      print('Doctor profile image uploaded successfully');
      return downloadUrl;
    } catch (e) {
      print('Error uploading doctor profile image: $e');
      return null;
    }
  }

  static Future<bool> deleteProfileImage(String imageUrl) async {
    try {
      final Reference storageRef = storage.refFromURL(imageUrl);
      await storageRef.delete();
      print('Doctor profile image deleted successfully');
      return true;
    } catch (e) {
      print('Error deleting doctor profile image: $e');
      return false;
    }
  }

  static Future<bool> saveDoctorProfile(DoctorController controller) async {
    try {
      final User? user = FirebaseAuth.instance.currentUser;
      if (user == null) {
        print('No user logged in');
        return false;
      }

      final String uid = user.uid;
      final Doctor doctorData = controller.model;
      String? imageUrl;

      if (doctorData.profileImage != null) {
        final File imageFile = File(doctorData.profileImage!);
        imageUrl = await uploadProfileImage(imageFile);
        if (imageUrl == null) {
          print('Failed to upload doctor profile image');
          return false;
        }
      }

      final Map<String, dynamic> doctorJson = doctorData.toJson();
      doctorJson['createdAt'] = FieldValue.serverTimestamp();
      doctorJson['updatedAt'] = FieldValue.serverTimestamp();
      doctorJson['uid'] = uid;
      doctorJson['profileImageUrl'] = imageUrl;

      await db.collection(doctorProfileCollectionName).doc(uid).set(doctorJson);

      print('Doctor profile saved successfully');
      return true;
    } catch (e) {
      print('Error saving doctor profile: $e');
      return false;
    }
  }

  static Future<bool> updateDoctorProfile(Doctor doctor) async {
    try {
      final User? user = FirebaseAuth.instance.currentUser;
      if (user == null) {
        print('No user logged in');
        return false;
      }

      final String uid = user.uid;
      String? imageUrl;

      if (doctor.profileImage != null) {
        // Delete old profile image if exists
        final DocumentSnapshot oldDoc =
            await db.collection(doctorProfileCollectionName).doc(uid).get();
        if (oldDoc.exists) {
          final oldData = oldDoc.data() as Map<String, dynamic>;
          final String? oldImageUrl = oldData['profileImageUrl'];
          if (oldImageUrl != null) {
            await deleteProfileImage(oldImageUrl);
          }
        }

        // Upload new profile image
        final File imageFile = File(doctor.profileImage!);
        imageUrl = await uploadProfileImage(imageFile);
        if (imageUrl == null) {
          print('Failed to upload new doctor profile image');
          return false;
        }
      }

      final Map<String, dynamic> doctorJson = doctor.toJson();
      doctorJson['updatedAt'] = FieldValue.serverTimestamp();
      if (imageUrl != null) {
        doctorJson['profileImageUrl'] = imageUrl;
      }

      await db
          .collection(doctorProfileCollectionName)
          .doc(uid)
          .update(doctorJson);

      print('Doctor profile updated successfully');
      return true;
    } catch (e) {
      print('Error updating doctor profile: $e');
      return false;
    }
  }

  static Future<bool> deleteDoctorProfile() async {
    try {
      final User? user = FirebaseAuth.instance.currentUser;
      if (user == null) {
        print('No user logged in');
        return false;
      }

      final String uid = user.uid;
      // Delete profile image if exists
      final DocumentSnapshot doc =
          await db.collection(doctorProfileCollectionName).doc(uid).get();
      if (doc.exists) {
        final data = doc.data() as Map<String, dynamic>;
        final String? imageUrl = data['profileImageUrl'];
        if (imageUrl != null) {
          await deleteProfileImage(imageUrl);
        }
      }

      await db.collection(doctorProfileCollectionName).doc(uid).delete();

      print('Doctor profile deleted successfully');
      return true;
    } catch (e) {
      print('Error deleting doctor profile: $e');
      return false;
    }
  }

  static Future<Doctor?> getDoctorProfile() async {
    try {
      final User? user = FirebaseAuth.instance.currentUser;
      if (user == null) {
        print('No user logged in');
        return null;
      }

      final String uid = user.uid;
      final DocumentSnapshot doc =
          await db.collection(doctorProfileCollectionName).doc(uid).get();

      if (!doc.exists) {
        print('No doctor profile found for this user');
        return null;
      }

      final data = doc.data() as Map<String, dynamic>;
      return Doctor.fromJson(data);
    } catch (e) {
      print('Error fetching doctor profile: $e');
      return null;
    }
  }

  static Future<bool> isLicenseNumberDuplicate(String licenseNumber) async {
    try {
      final querySnapshot = await db
          .collection(doctorProfileCollectionName)
          .where('licenseNumber', isEqualTo: licenseNumber)
          .get();

      return querySnapshot.docs.isNotEmpty;
    } catch (e) {
      print('Error checking license number: $e');
      return false;
    }
  }
}
