import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/api/login_api_client.dart';

import '../../models/user.dart';
import '../../views/pages/user/land_page.dart';
import '../http_status_manger/http_status_manger.dart';
import '../localization/localization.dart';
import 'loading_notifier.dart';
import 'settings/setting_provider.dart';

class UserProvider extends LoadingNotifier {
  /// - [user] data will be null
  /// - loading process will stop
  void reset() {
    UserApiClient().user = null;
    stopLoading();
  }

  /// ## Login & Fill [UserApiClient.user] data
  /// - onSuccess and user is Active : push to [LandPage]
  /// - onSuccess and user isn't Active : toast message will appears
  /// - onError : SnackBar will appears
  Future login(BuildContext context, {required User user}) async {
    final subtitle = AppLocalization.of(context)?.subtitle;
    waitApiRequest(
      () async {
        await UserApiClient().login(user: user);
      },
      onSuccess: () {
        if (context.mounted) {
          Provider.of<SettingProvider>(context, listen: false).setUser(UserApiClient().user ?? User());
          if (UserApiClient().user?.isActive ?? false) {
            Navigator.of(context).pushNamed(LandPage.id);
          } else {
            Fluttertoast.showToast(msg: subtitle?.activationAlert ?? "");
          }
        }
      },
      onError: (error) {
        String errorMessage = error.error?.errorCode == 400 ? subtitle?.wrongEmailOrPassword ?? "" : HttpStatusManger.getStatusMessage(status: error.error?.errorCode, subtitle: subtitle);
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage)));
      },
    );
  }

  /// ## Register & Fill [UserApiClient.user] data
  /// - onSuccess : toast message will appears
  /// - onError : SnackBar will appears
  Future register(BuildContext context, {required User newUser}) async {
    final subtitle = AppLocalization.of(context)?.subtitle;
    if (newUser.hospital == null) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(subtitle?.hospitalRequired ?? "")));
      return;
    }
    if (newUser.department == null) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(subtitle?.unitRequired ?? "")));
      return;
    }
    waitApiRequest(
      () async {
        await UserApiClient().register(newUser: newUser);
      },
      onSuccess: () {
        Fluttertoast.showToast(msg: subtitle?.activationAlert ?? "");
        Navigator.of(context).pop();
      },
      onError: (error) {
        String? errorMessage = error.error?.errorCode == 402
            ? subtitle?.nameExist
            : error.error?.errorCode == 401
                ? subtitle?.emailExist
                : HttpStatusManger.getStatusMessage(status: error.error?.errorCode, subtitle: subtitle);
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage ?? "")));
      },
    );
  }

  /// ## Update current user profile
  /// - onSuccess : SnackBar will appears
  /// - onError : SnackBar will appears
  Future updateProfile(BuildContext context, {required User updatedUser}) async {
    final subtitle = AppLocalization.of(context)?.subtitle;
    if (updatedUser.department?.id == null) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(subtitle?.unitRequired ?? "")));
      return;
    }
    waitApiRequest(
      () async {
        await UserApiClient().updateProfile(updatedUser: updatedUser);
      },
      onSuccess: () {
        Provider.of<SettingProvider>(context, listen: false).setUser(UserApiClient().user!);
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(subtitle?.requestCompleteSuccessfully ?? '')));
      },
      onError: (error) {
        String errorMessage = HttpStatusManger.getStatusMessage(status: error.error?.errorCode, subtitle: subtitle);
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage)));
      },
    );
  }
}
