import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/enum/user_enum.dart';
import 'package:hamlemuhcrm/core/init/cache/cache_manager.dart';
import 'package:hamlemuhcrm/data/repo/login_repository.dart';
import 'package:hamlemuhcrm/features/auth/login/model/get_profile.dart';
import 'package:hamlemuhcrm/features/auth/login/model/login_response.dart';
import 'package:hamlemuhcrm/features/home/cubit/home_custom_cubit.dart';
import 'package:hamlemuhcrm/features/profile/model/profile_detail.dart';

part 'login_state.dart';

class LoginCubit extends Cubit<LoginState> {
  LoginCubit(this._homeCustomCubit) : super(LoginState.initial());

  final HomeCustomCubit _homeCustomCubit;

  //token
  late String id;
  late String message;
  late String durum;
  late String userfirmId;
  late String tip;
  late String userimage;
  late String iseGirisTarihi;
  late String unvanId;
  late String unvanAd;
  late String hakkettigiyillikizingunsayisi;
  late String kullanilmisyillikizingunsayisi;
  late String kalanyillikizinhakkigunsayisi;
  late String token;

  ////getprofile
  String ad = "";
  String soyad = "";
  String email = "";
  String bildirimMail = "";
  String ceptelefon = "";

  var loginRepo = LoginRepository();

  void loginOl(String eposta, String sifre) async {
    emit(state.copyWith(
        isLoading: true,
        isError: false,
        isFieldEmpty: false,
        isComplete: false,
        isCorrect: false,
        isLoggedIn: false));

    ////////////////////////////////////////////////////////
    if (eposta.isEmpty || sifre.isEmpty) {
      emit(state.copyWith(
          isFieldEmpty: true,
          isLoading: false,
          isError: false,
          isComplete: false,
          isLoggedIn: false,
          isCorrect: false));
      return;
    }
    try {
      final loginResponse = await loginRepo.loginOlRepo(eposta, sifre);
      if (loginResponse != null && loginResponse.state == "1") {
        saveChangeValue(loginResponse);

        final getProfileResponse = await loginRepo.profilGetir(token, id);
        if (getProfileResponse != null) {
          _getProfileSaveChanges(getProfileResponse);
          await _homeChangeValue();

          return emit(state.copyWith(
            isLoggedIn: true,
            isComplete: true,
            isError: false,
            isLoading: false,
            isFieldEmpty: false,
            isCorrect: false,
          ));
        } else {
          return emit(state.copyWith(
              isCorrect: true,
              isLoading: false,
              isFieldEmpty: false,
              isError: false,
              isLoggedIn: false,
              isComplete: false));
        }
      } else if (loginResponse != null && loginResponse.state == "0") {
        return emit(state.copyWith(
          isCorrect: true,
          isLoading: false,
          isFieldEmpty: false,
          isError: false,
          isLoggedIn: false,
          isComplete: false,
        ));
      }
    } catch (e) {
      debugPrint(e.toString());
      emit(state.copyWith(
          isError: true,
          isLoading: false,
          isLoggedIn: false,
          isComplete: false,
          isFieldEmpty: false,
          isCorrect: false));
    }
  }

  Future<void> _homeChangeValue() async {
    await Future.microtask(() => [
          _homeCustomCubit.musteriSayisiGetir(id, userfirmId, tip, token, id),
          _homeCustomCubit.personelSayisiGetir(userfirmId, tip, token, id),
          _homeCustomCubit.projeSayisiGetir(token, id)
        ]);
  }

  void setNewProfileValues(ProfileDetail detail) async {
    ceptelefon = detail.telNumber;
  }

  void saveChangeValue(LoginResponseModel loginResponse) async {
    id = loginResponse.userId ?? "0";
    message = loginResponse.message ?? "default";
    durum = loginResponse.state ?? "0";
    userfirmId = loginResponse.userfirmId ?? "0";
    tip = loginResponse.tip ?? "0";
    userimage = loginResponse.userimage ?? "empty.png";
    hakkettigiyillikizingunsayisi =
        loginResponse.hakkettigiyillikizingunsayisi ?? "0";
    kullanilmisyillikizingunsayisi =
        loginResponse.kullanilmisyillikizingunsayisi ?? "0";
    kalanyillikizinhakkigunsayisi =
        loginResponse.kalanyillikizinhakkigunsayisi ?? "0";
    iseGirisTarihi = loginResponse.iseGirisTarihi ?? "01.01.2000";
    unvanId = loginResponse.unvanid ?? "0";
    unvanAd = loginResponse.unvanad ?? "Personel";
    token = loginResponse.token ?? "0";
    // token'ı ve id değerlerini bu aşamada kaydediyoruz
    await tokenKaydet(token, id, userfirmId);
  }

  void _getProfileSaveChanges(GetProfileModel getProfileResponse) {
    ad = getProfileResponse.firstName ?? "";
    soyad = getProfileResponse.lastName ?? "";
    email = getProfileResponse.email ?? "";
    ceptelefon = getProfileResponse.ceptelefon ?? "";
    bildirimMail =
        getProfileResponse.bildirimMail ?? (getProfileResponse.email ?? "");
  }

  void setUserInfo({
    //(splash) token ile giriş yapıldığında bu metot üzerinden gelen değerleri login cubit'e atayacak..
    required String token,
    required String id,
    required String message,
    required String durum,
    required String userfirmId,
    required String tip,
    required String userimage,
    required String iseGirisTarihi,
    required String unvanId,
    required String unvanAd,
    required String hakkettigiYillikizingunSayisi,
    required String kullanilmisYillikIzinGunSayisi,
    required String kalanyillikizinhakkigunsayisi,
    required String ad,
    required String soyad,
    required String email,
    required String bildirimMail,
    required String ceptelefon,
  }) {
    this.token = token;
    this.id = id;
    this.message = message;
    this.durum = durum;
    this.userfirmId = userfirmId;
    this.tip = tip;
    this.userimage = userimage;
    this.iseGirisTarihi = iseGirisTarihi;
    this.unvanId = unvanId;
    this.unvanAd = unvanAd;
    hakkettigiyillikizingunsayisi = hakkettigiYillikizingunSayisi;
    kullanilmisyillikizingunsayisi = kullanilmisYillikIzinGunSayisi;
    this.kalanyillikizinhakkigunsayisi = kalanyillikizinhakkigunsayisi;
    this.ad = ad;
    this.soyad = soyad;
    this.email = email;
    this.bildirimMail = bildirimMail;
    this.ceptelefon = ceptelefon;
  }

  Future<void> tokenKaydet(
      String token, String loginuserid, String userfirmid) async {
    await CacheManager.instance.addValue(UserEnum.token.toName, token);
    await CacheManager.instance.addValue(UserEnum.loginid.toName, loginuserid);
    await CacheManager.instance
        .addValue(UserEnum.userfirmid.toName, userfirmid);
  }

  Future<void> kayitliBilgileriSil() async {
    await CacheManager.instance.removeValue(UserEnum.token.toName);
    await CacheManager.instance.removeValue(UserEnum.loginid.toName);
    await CacheManager.instance.removeValue(UserEnum.userfirmid.toName);
  }
}
