import 'package:dio/dio.dart';
import 'package:qadirneyriz/config/config.dart';
import 'package:qadirneyriz/main.dart';
import 'package:qadirneyriz/setting/setting.dart';
import 'package:qadirneyriz/utils/result/result.dart';
import 'dart:io';

class AuthServices {
  String userAgent =
      Platform.isAndroid ? 'application/android' : 'application/ios';
  Future<Result?> loginApi({
    required String mobile,
    String? password,
    String? otp,
  }) async {
    String? token;

    token = await messaging.getToken();

    assert(password != null || otp != null);

    try {
      Map<String, String> headers = {
        "Accept": "application/json",
        "user-agent": userAgent
      };
      FormData formData;
      formData = password != null
          ? FormData.fromMap(
              {"mobile": mobile, "password": password, "device_id": token})
          : FormData.fromMap(
              {"mobile": mobile, "otp": otp, "device_id": token});

      // print('${formData.fields} resData');
      final res = await Dio().post(
          "${config.network.baseUrl}login?lang=${setting.userLocalDb.getUser().language}",
          data: formData,
          options: Options(headers: headers));

      if (res.statusCode == 200 || res.statusCode == 201) {
        setting.userLocalDb.saveUserField('token', res.data['token']);
        setting.userLocalDb.saveUserField('mobile', res.data['mobile']);
        setting.userLocalDb.saveUserField('name', res.data['name']);
        setting.userLocalDb.saveUserField('role', res.data['role']);
        setting.userLocalDb.saveUserField('access', res.data['access']);
        return Result(isOk: true, message: res.data['msg']);
      }
    } on DioException catch (e) {
      // print(e);
      return Result(
          isOk: false,
          errors: e.response?.data['errors'],
          message: e.response?.data['msg']);
    }
    return const Result(isOk: false);
  }

  Future<Result?> sendOtpApi({required String mobile}) async {
    try {
      Map<String, String> headers = {
        "Accept": "application/json",
        "user-agent": userAgent,
      };
      FormData formData = FormData.fromMap({"mobile": mobile});

      final res = await Dio().post(
          "${config.network.baseUrl}sendOtp?lang=${setting.userLocalDb.getUser().language}",
          data: formData,
          options: Options(headers: headers));

      if (res.statusCode == 200 || res.statusCode == 201) {
        return Result(isOk: true, message: res.data['msg']);
      }
    } on DioException catch (e) {
      return Result(
          isOk: false,
          errors: e.response?.data['errors'],
          message: e.response?.data['msg']);
    }
    return const Result(isOk: false);
  }

  Future<Result?> checkLoginApi() async {
    final userRole = setting.userLocalDb.getUser().role;

    try {
      Map<String, String> headers = {"Accept": "application/json"};
      String dataToken = setting.userLocalDb.getUser().token!;

      if (dataToken != '') {
        headers['Authorization'] = "Bearer $dataToken";
      }
      // print('$dataToken datatokoen');

      // لینک API
      final apiUrl = userRole != 1
          ? "${config.network.baseUrl}admin/checkLogin"
          : "${config.network.baseUrl}user/checkLogin";

      final res = await Dio().get(
        apiUrl,
        options: Options(headers: headers),
      );

      if (res.statusCode == 200 || res.statusCode == 201) {
        return Result(isOk: true, message: res.data['msg']);
      }
    } on DioException catch (e) {
      return Result(
        isOk: false,
        errors: e.response?.data['errors'],
        message: e.response?.data['msg'],
      );
    }

    return const Result(isOk: false);
  }

  Future<Result?> authLog() async {
    try {
      print("Starting authLog...");
      Map<String, String> headers = {
        "Accept": "application/json",
        "User-Agent": Platform.isAndroid ? "android" : "ios"
      };
      String dataToken = setting.userLocalDb.getUser().token!;
      print("Retrieved token: $dataToken");

      if (dataToken != '') {
        headers['Authorization'] = "Bearer $dataToken";
        print("Authorization header set.");
      }

      // لینک API
      final apiUrl = "${config.network.baseUrl}auth-log";
      print("API URL: $apiUrl");

      final res = await Dio().post(
        apiUrl,
        options: Options(headers: headers),
      );

      print("Response received: ${res.statusCode}");
      if (res.statusCode == 200 || res.statusCode == 204) {
        print("Success: ${res.data}");
        return Result(isOk: true, message: res.data['msg']);
      }
    } on DioException catch (e) {
      print("DioException occurred: ${e.response?.data}");
      return Result(
        isOk: false,
        errors: e.response?.data['errors'],
        message: e.response?.data['msg'],
      );
    } catch (e) {
      print("Unexpected error: $e");
    }

    print("Returning default failure result.");
    return const Result(isOk: false);
  }
}
