import 'dart:convert';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mobile_pos/model/personal_information_model.dart';

import '../Provider/user_role_provider.dart';
import '../currency.dart';

class ProfileRepo {
  DatabaseReference ref = FirebaseDatabase.instance.ref();

  Future<PersonalInformationModel> getDetails() async {
    PersonalInformationModel personalInfo = PersonalInformationModel(
        companyName: 'Loading...',
        businessCategory: 'Loading...',
        countryName: 'Loading...',
        language: 'Loading...',
        phoneNumber: 'Loading...',
        gst: '',
        pictureUrl: 'https://cdn.pixabay.com/photo/2017/06/13/12/53/profile-2398782_960_720.png');
    final userRef = FirebaseDatabase.instance.ref(constUserId).child('Personal Information');

    final model = await userRef.get();
    userRef.keepSynced(true);
    var data = jsonDecode(jsonEncode(model.value));
    if (data == null) {
      return personalInfo;
    } else {
      return PersonalInformationModel.fromJson(data);
    }
  }

  Future<bool> isProfileSetupDone({required String email, required WidgetRef providerRef}) async {
    await checkAndSetUserData(email: email, ref: providerRef);
    final model = await ref.child('$constUserId/Personal Information').get();
    var data = jsonDecode(jsonEncode(model.value));
    if (data == null && isSubUser == false) {
      return false;
    } else {
      return true;
    }
  }

  Future<void> checkAndSetUserData({
    required String? email,
    required WidgetRef ref,
  }) async {
    final userRoleData = await ref.watch(allUserRoleProvider.future);

    bool isNotFound = true;
    for (var element in userRoleData) {
      if (element.userEmail == email) {
        isNotFound = false;
        await CurrentUserData().putUserData(
          userId: element.databaseId ?? '',
          subUser: true,
          title: element.userTitle ?? '',
          email: element.userEmail ?? '',
        );
        subUserTitle = element.userTitle ?? '';
        break;
      }
    }
    if (isNotFound) {
      await CurrentUserData().putUserData(
        userId: FirebaseAuth.instance.currentUser!.uid,
        subUser: false,
        title: '',
        email: '',
      );
    }
  }
}
