import 'dart:convert';

import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/models/user_model.dart';
import 'package:http/http.dart' as http;

class AuthService {
  Future<UserModel> register({
    required String name,
    required String email,
    required String password,
    required String phoneNumber,
  }) async {
    print('[DEBUG] Register called with: name=$name, email=$email, phone=$phoneNumber');
    Uri url = Uri.parse('$baseUrl/auth/register');
    var body = jsonEncode({
      'name': name,
      'email': email,
      'password': password,
      'phone': phoneNumber,
    });

    print('[DEBUG] Register URL: $url');
    print('[DEBUG] Register Body: $body');

    var response = await http.post(url, headers: baseHeader, body: body);
    print('[DEBUG] Register Response: ${response.statusCode} ${response.body}');
    if (response.statusCode == 201) {
      return UserModel.fromJson(jsonDecode(response.body)['data']);
    } else if (response.statusCode == 403) {
      var responseData = jsonDecode(response.body)['data']['message'];
      print('[DEBUG] Register 403 ResponseData: $responseData');
      if (responseData.containsKey('email')) {
        throw ('Failed\n\nEmail sudah terdaftar');
      } else if (responseData.containsKey('phone')) {
        throw ('Failed\n\nNomor HP sudah terdaftar');
      } else {
        throw ('Registrasi gagal. Mohon coba lagi.');
      }
    } else {
      throw ('Registrasi gagal. Mohon coba lagi.');
    }
  }

  Future<UserModel> login(
      {required String email, required String password}) async {
    print('[DEBUG] Login called with: email=$email');
    Uri url = Uri.parse('$baseUrl/auth/mobile/login');
    var body = jsonEncode({
      'email': email,
      'password': password,
    });
    print('[DEBUG] Login URL: $url');
    print('[DEBUG] Login Body: $body');
    var response = await http.post(url, headers: baseHeader, body: body);
    print('[DEBUG] Login Response: ${response.statusCode} ${response.body}');
    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'];
      UserModel user = UserModel.fromJson(data);
      user.token = data['token'];

      await UsersInfo().setToken(user.token!);

      return user;
    } else {
      throw Exception('Gagal login mobile');
    }
  }

  Future<bool> googleSignInAuth({
    required String idToken,
  }) async {
    print('[DEBUG] GoogleSignInAuth called with idToken=$idToken');
    Uri url = Uri.parse('$baseUrl/auth/googlecheck/signin');
    var body = jsonEncode({
      'id_token': idToken,
    });
    print('[DEBUG] GoogleSignInAuth URL: $url');
    print('[DEBUG] GoogleSignInAuth Body: $body');
    var response = await http.post(url, headers: baseHeader, body: body);
    print('[DEBUG] GoogleSignInAuth Response: ${response.statusCode} ${response.body}');

    if (response.statusCode == 200 || response.statusCode == 403) {
      var res = jsonDecode(response.body)['data'];
      print('[DEBUG] GoogleSignInAuth Token: ${res['token']}');
      await UsersInfo().setToken(res['token']);
      return true;
    } else if (response.statusCode == 400) {
      print("Gagal login 400 ${response.body}");
      throw Exception('Akun anda belum terdaftar');
    } else {
      print("Gagal login google ${response.body}");
      throw Exception('Gagal login');
    }
  }

  Future<bool> checkToken(String? token) async {
    print('[DEBUG] checkToken called with token=$token');
    Uri url = Uri.parse('$baseUrl/users/course/my');
    print('[DEBUG] checkToken URL: $url');
    var response = await http.get(url, headers: headerWithToken(token));
    print('[DEBUG] checkToken Response: ${response.statusCode} ${response.body}');
    if (response.statusCode == 200) {
      print("Berhasil token ${response.body}");
      return false;
    } else if (response.statusCode == 404) {
      print("404 token ${response.body}");
      return false;
    } else {
      print("Gagal token ${response.body}");
      return true;
    }
  }
}
