import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/rendering.dart';
import 'package:syncrow_web/pages/roles_and_permission/model/edit_user_model.dart';
import 'package:syncrow_web/pages/roles_and_permission/model/role_type_model.dart';
import 'package:syncrow_web/pages/roles_and_permission/model/roles_user_model.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/model/permission_option_model.dart';
import 'package:syncrow_web/services/api/http_service.dart';
import 'package:syncrow_web/utils/constants/api_const.dart';

class UserPermissionApi {
  static final HTTPService _httpService = HTTPService();

  Future<List<RolesUserModel>> fetchUsers(String projectId) async {
    try {
      final response = await _httpService.get(
        path: ApiEndpoints.getUsers.replaceAll('{projectId}', projectId),
        showServerMessage: true,
        expectedResponseModel: (json) {
          debugPrint('fetchUsers Response: $json');
          final List<dynamic> data = json['data'] ?? [];
          return data.map((item) => RolesUserModel.fromJson(item)).toList();
        },
      );
      return response;
    } catch (e, stackTrace) {
      debugPrint('Error in fetchUsers: $e');
      rethrow;
    }
  }

  fetchRoles() async {
    final response = await _httpService.get(
      path: ApiEndpoints.roleTypes,
      showServerMessage: true,
      expectedResponseModel: (json) {
        final List<RoleTypeModel> fetchedRoles =
            (json['data'] as List).map((item) => RoleTypeModel.fromJson(item)).toList();
        return fetchedRoles;
      },
    );
    return response;
  }

  Future<List<PermissionOption>> fetchPermission(roleUuid) async {
    final response = await _httpService.get(
      path: ApiEndpoints.permission.replaceAll("roleUuid", roleUuid),
      showServerMessage: true,
      expectedResponseModel: (json) {
        return (json as List).map((data) => PermissionOption.fromJson(data)).toList();
      },
    );
    return response ?? [];
  }

  Future<bool> sendInviteUser({
    String? firstName,
    String? lastName,
    String? email,
    String? jobTitle,
    String? phoneNumber,
    String? roleUuid,
    List<String>? spaceUuids,
    required String projectUuid,
  }) async {
    try {
      final body = <String, dynamic>{
        "firstName": firstName,
        "lastName": lastName,
        "email": email,
        "jobTitle": jobTitle != '' ? jobTitle : null,
        "phoneNumber": phoneNumber != '' ? phoneNumber : null,
        "roleUuid": roleUuid,
        "projectUuid": projectUuid,
        "spaceUuids": spaceUuids,
      };
      final response = await _httpService.post(
        path: ApiEndpoints.inviteUser,
        showServerMessage: true,
        body: jsonEncode(body),
        expectedResponseModel: (json) {
          if (json['statusCode'] != 400) {
            return json["success"];
          } else {
            return false;
          }
        },
      );

      return response ?? [];
    } on DioException catch (e) {
      return false;
    } catch (e) {
      return false;
    }
  }

  Future<String?> checkEmail(String email) async {
    try {
      final response = await _httpService.post(
        path: ApiEndpoints.checkEmail,
        showServerMessage: true,
        body: {"email": email},
        expectedResponseModel: (json) {
          if (json['statusCode'] != 400) {
            var message = json["message"];
            if (message is String) {
              return message;
            } else {
              return 'Unexpected message format';
            }
          }
          return null;
        },
      );
      return response ?? 'Unknown error occurred';
    } on DioException catch (e) {
      final errorMessage = e.response?.data['error']['message'];
      return errorMessage;
    } catch (e) {
      return e.toString();
    }
  }

  Future<EditUserModel?> fetchUserById(userUuid, String projectId) async {
    final response = await _httpService.get(
      path: ApiEndpoints.getUserById
          .replaceAll("{userUuid}", userUuid)
          .replaceAll("{projectId}", projectId),
      showServerMessage: true,
      expectedResponseModel: (json) {
        EditUserModel res = EditUserModel.fromJson(json['data']);
        return res;
      },
    );
    return response;
  }

  Future<bool> editInviteUser({
    String? firstName,
    String? userId,
    String? lastName,
    String? jobTitle,
    String? phoneNumber,
    String? roleUuid,
    List<String>? spaceUuids,
    required String projectUuid,
  }) async {
    try {
      final body = <String, dynamic>{
        "firstName": firstName,
        "lastName": lastName,
        "jobTitle": jobTitle != '' ? jobTitle : " ",
        "phoneNumber": phoneNumber != '' ? phoneNumber : " ",
        "roleUuid": roleUuid,
        "projectUuid": projectUuid,
        "spaceUuids": spaceUuids,
      };
      final response = await _httpService.put(
        path: ApiEndpoints.editUser.replaceAll('{inviteUserUuid}', userId!),
        body: jsonEncode(body),
        expectedResponseModel: (json) {
          if (json['statusCode'] != 400) {
            return json["success"];
          } else {
            return false;
          }
        },
      );
      return response;
    } on DioException catch (e) {
      return false;
    } catch (e) {
      return false;
    }
  }

  Future<bool> deleteUserById(userUuid) async {
    try {
      final response = await _httpService.delete(
        path: ApiEndpoints.deleteUser.replaceAll("{inviteUserUuid}", userUuid),
        showServerMessage: true,
        expectedResponseModel: (json) {
          return json['success'];
        },
      );
      return response;
    } catch (e) {
      return false;
    }
  }

  Future<bool> changeUserStatusById(userUuid, status, String projectUuid) async {
    try {
      Map<String, dynamic> bodya = {"disable": status, "projectUuid": projectUuid};

      final response = await _httpService.put(
        path: ApiEndpoints.changeUserStatus.replaceAll("{invitedUserUuid}", userUuid),
        body: bodya,
        expectedResponseModel: (json) {
          return json['success'];
        },
      );

      return response;
    } catch (e) {
      return false;
    }
  }
}
