import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:medora/data/models/telemed_user.dart';

class DataService {
  static final String profileCollectionName =
      dotenv.env['PROFILE_COLLECTION_NAME']!;
  static final db = FirebaseFirestore.instance;
  static final auth = FirebaseAuth.instance;

  static Future<Map<String, dynamic>> createUserProfile({
    required String email,
    required String password,
    required String userType,
    String? phoneNumber,
  }) async {
    try {
      final UserCredential userCredential =
          await auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );

      final User? user = userCredential.user;
      if (user == null) {
        return {'success': false, 'message': 'Failed to create user account'};
      }

      final profiles = db.collection(profileCollectionName);
      await profiles.doc(user.uid).set({
        'UserType': userType,
        'email': email,
        'phoneNumber': phoneNumber,
        'createdAt': FieldValue.serverTimestamp(),
      });

      return {'success': true, 'message': 'Account created successfully'};
    } on FirebaseAuthException catch (e) {
      String message;
      switch (e.code) {
        case 'email-already-in-use':
          message =
              'This email is already registered. Please use a different email or sign in.';
          break;
        case 'invalid-email':
          message = 'The email address is invalid. Please check and try again.';
          break;
        case 'operation-not-allowed':
          message =
              'Email/password accounts are not enabled. Please contact support.';
          break;
        case 'weak-password':
          message = 'The password is too weak. Please use a stronger password.';
          break;
        default:
          message = 'An error occurred during registration: ${e.message}';
      }
      return {'success': false, 'message': message};
    } on FirebaseException catch (e) {
      return {'success': false, 'message': 'Database error: ${e.message}'};
    } catch (e) {
      return {
        'success': false,
        'message': 'An unexpected error occurred. Please try again.'
      };
    }
  }

  static User? getCurrentUser() {
    return auth.currentUser;
  }

  static Future<TelemedUser?> getProfile() async {
    try {
      final user = getCurrentUser();
      if (user == null) return null;

      final profile =
          await db.collection(profileCollectionName).doc(user.uid).get();
      if (!profile.exists) return null;

      final profileData = profile.data();
      if (profileData == null) return null;

      return TelemedUser.fromJson(profileData, user.uid);
    } catch (e) {
      print('Error getting profile: $e');
      return null;
    }
  }
}
