import 'dart:convert';
import 'dart:io';

import 'package:flutter_pos_ecommerce/core/constants/global_variable.dart';
import 'package:flutter_pos_ecommerce/module/ecommerce/data/datasources/auth_local_datasource.dart';
import 'package:flutter_pos_ecommerce/module/ecommerce/data/models/responses/auth_response_model.dart';
import 'package:http/http.dart' as http;
import 'package:dartz/dartz.dart';

class AuthRemoteDatasource {
  Future<Either<String, AuthResponseModel>> login(
      String email, String password) async {
    final response = await http.post(
        Uri.parse('${GlobalVariable.baseUrl}/api/login'),
        body: {'email': email, 'password': password});

    if (response.statusCode == 200) {
      return Right(AuthResponseModel.fromJson(response.body));
    } else {
      String res = response.body;
      Map<String, dynamic> resData = jsonDecode(res);
      return Left(resData['message']);
    }
  }

  Future<Either<String, AuthResponseModel>> register(
      String name, String email, String phone, String password) async {
    final response = await http
        .post(Uri.parse('${GlobalVariable.baseUrl}/api/register'), body: {
      'name': name,
      'email': email,
      'phone': phone,
      'password': password
    });

    if (response.statusCode == 201) {
      return Right(AuthResponseModel.fromJson(response.body));
    } else {
      String res = response.body;
      Map<String, dynamic> resData = jsonDecode(res);
      return Left(resData['message']);
    }
  }

  Future<Either<String, String>> logout() async {
    final authData = await AuthLocalDatasource().getAuthData();
    final response = await http.post(
        Uri.parse('${GlobalVariable.baseUrl}/api/logout'),
        headers: {'Authorization': 'Bearer ${authData?.accessToken}'});
    if (response.statusCode == 200) {
      AuthLocalDatasource().removeAuthData();
      return Right(response.body);
    } else {
      return Left(response.body);
    }
  }

  Future<Either<String, String>> updateFcmToken(String fcmToken) async {
    final authData = await AuthLocalDatasource().getAuthData();
    final response = await http.post(
      Uri.parse('${GlobalVariable.baseUrl}/api/update-fcm'),
      headers: {
        'Authorization': 'Bearer ${authData?.accessToken}',
        'Accept': 'application/json',
      },
      body: {'fcm_id': fcmToken},
    );

    if (response.statusCode == 200) {
      return Right(response.body);
    } else {
      return Left(response.body);
    }
  }

  Future<Either<String, Map<String, dynamic>>> getProfile() async {
    final authData = await AuthLocalDatasource().getAuthData();
    final response = await http.get(
      Uri.parse('${GlobalVariable.baseUrl}/api/profile'),
      headers: {
        'Authorization': 'Bearer ${authData?.accessToken}',
      },
    );
    if (response.statusCode == 200) {
      return Right(jsonDecode(response.body));
    } else {
      return const Left('Failed to fetch profile');
    }
  }

  Future<Either<String, String>> updateProfile({
    required String name,
    required String email,
    required String phone,
    File? foto,
  }) async {
    final authData = await AuthLocalDatasource().getAuthData();

    if (foto == null) {
      final authData = await AuthLocalDatasource().getAuthData();
      final response = await http.put(
        Uri.parse("${GlobalVariable.baseUrl}/api/profile"),
        headers: {
          'Authorization': 'Bearer ${authData!.accessToken}',
          'Accept': 'application/json',
        },
        body: {'name': name, 'email': email, 'phone': phone},
      );

      print(response.body);
      if (response.statusCode == 200) {
        return const Right('Profile Berhasil di Perbarui');
      } else {
        return const Left("Internal Server Error");
      }
    } else {
      var request = http.MultipartRequest(
        'POST',
        Uri.parse('${GlobalVariable.baseUrl}/api/profile'),
      );

      request.headers['Authorization'] = 'Bearer ${authData?.accessToken}';

      request.fields['name'] = name;
      request.fields['email'] = email;
      request.fields['phone'] = phone;

      // Periksa apakah foto tidak null
      request.files.add(
        await http.MultipartFile.fromPath(
          'foto',
          foto.path,
        ),
      );

      var response = await request.send();

      if (response.statusCode == 200) {
        var responseData = await http.Response.fromStream(response);
        print('Response data: ${responseData.body}');
        return const Right('Profile Berhasil di Perbarui');
      } else {
        var responseData = await http.Response.fromStream(response);
        print('Error response data: ${responseData.body}');
        return const Left('Failed to update profile');
      }
    }
  }

  
}
