// import 'package:just_audio/just_audio.dart';
import 'package:just_audio/just_audio.dart';
import 'package:rxdart/rxdart.dart';
import 'package:voice_buddies/app/models/common_model.dart';
import 'package:voice_buddies/app/models/login_model.dart';
import 'package:voice_buddies/app/modules/user_details/controllers/user_details_controller.dart';
import 'package:voice_buddies/app/widget/base_controller.dart';

import '../../../utils/all_imports.dart';
import '../../../widget/common_seekbar.dart';

class EditProfileController extends BaseController {
  List<CommonModel> userDetails = [];
  final player = AudioPlayer();
  RxString path = "".obs;

  ///audio stream
  Stream<PositionData> get positionDataStream {
    return Rx.combineLatest3<Duration, Duration, Duration?, PositionData>(
      player.positionStream,
      player.bufferedPositionStream,
      player.durationStream,
      (position, bufferedPosition, duration) => PositionData(
        position,
        bufferedPosition,
        duration ?? Duration.zero,
      ),
    );
  }

  ///assign user data to model from local storage
  userProfileDetails({gender, age, currentlyIAm, whereILive, spokenLanguages, recording}) async {
    userDetails = [
      CommonModel(
        name: AppStrings.email,
        details: loginData?.email ?? "",
      ),
      CommonModel(
        name: AppStrings.phoneNumber,
        details: "+${loginData?.ccode} ${loginData?.phone}",
      ),
      CommonModel(
        name: AppStrings.gender,
        details: gender,
      ),
      CommonModel(
        name: AppStrings.age,
        details: age,
      ),
      CommonModel(
        name: AppStrings.currentlyIAm,
        details: currentlyIAm,
      ),
      CommonModel(
        name: AppStrings.whereILive,
        details: whereILive,
      ),
      CommonModel(
        name: AppStrings.spokenLanguages,
        details: spokenLanguages,
      ),
      CommonModel(
        name: AppStrings.recording,
        details: recording,
      ),
    ];

    if (recording.toString().isURL) {
      printAction(" recording.toString() =-=-=-=-=-=-=-=-=-=-=-=->>${recording.toString()}");
      await player.setAudioSource(AudioSource.uri(Uri.parse(recording)));
      Loading.dismiss();
    } else {
      await player.setAudioSource(AudioSource.file(recording));
    }
    printAction("audio file==$recording");
    update();
  }

  ///selected user details assign to model
  editedDetails() {
    userDetails.clear();
    userProfileDetails(
      gender: Get.find<UserDetailsController>().selectedGender.value,
      age: Get.find<UserDetailsController>().selectedAge.value,
      currentlyIAm: Get.find<UserDetailsController>().selectedCurrentlyIAm.value,
      whereILive: Get.find<UserDetailsController>().selectedCountry.value,
      spokenLanguages: Get.find<UserDetailsController>().selectedLanguage.value,
      recording: Get.find<UserDetailsController>().isTips.value ? loginData?.voice : Get.find<UserDetailsController>().path,
    );
    printAction(Get.find<UserDetailsController>().path.toString());
    update();
  }

  @override
  void onInit() {
    getUserData();
    printAction("loginData?.voiceloginData?.voiceloginData?.voice ${loginData?.voice}");
    userProfileDetails(gender: loginData!.gender, age: loginData!.age, currentlyIAm: loginData!.iAm, whereILive: loginData!.iLive, spokenLanguages: loginData!.spoken, recording: loginData?.voice);
    super.onInit();
  }

  /// UpdateProfile api
  updateProfile() async {
    await player.stop();

    printAction("gender is in small==${userDetails[2].details}");
    FormData formData = userDetails[7].details.isURL
        ? FormData.fromMap({
            "gender": userDetails[2].details,
            "age": userDetails[3].details,
            "i_am": userDetails[4].details,
            "i_live": userDetails[5].details,
            "spoken": userDetails[6].details,
            "user_id": loginData?.userId,
          })
        : FormData.fromMap({
            "gender": userDetails[2].details,
            "age": userDetails[3].details,
            "i_am": userDetails[4].details,
            "i_live": userDetails[5].details,
            "spoken": userDetails[6].details,
            "user_id": loginData?.userId,
            "voice": MultipartFile.fromFileSync(userDetails[7].details, filename: userDetails[7].details.split("/").last),
          });

    final data = await APIFunction().apiCall(
      apiName: Constants.updateProfile,
      params: formData,
      token: loginData?.token,
    );
    LoginDataModel model = LoginDataModel.fromJson(data);

    if (model.responseCode == 1) {
      await getStorageData.saveObject(getStorageData.loginData, model.data!);
      Get.toNamed(Routes.DONE, arguments: AppStrings.editProfile);
    } else {
      utils.showSnackBar(message: model.responseMsg!, statusCode: model.responseCode);
    }
  }

  @override
  void onClose() {
    player.stop();
    if (!isClosed) {
      player.dispose();
    }
    super.onClose();
  }
}
