import 'dart:developer';

import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart';
import 'package:enaklo_pos/core/network/dio_client.dart';
import 'package:enaklo_pos/data/models/request/product_request_model.dart';
import 'package:enaklo_pos/data/models/response/add_product_response_model.dart';
import 'package:enaklo_pos/data/models/response/product_response_model.dart';

import '../../core/constants/variables.dart';
import 'auth_local_datasource.dart';

class ProductRemoteDatasource {
  final Dio dio = DioClient.instance;

  Future<Either<String, ProductResponseModel>> getProducts({
    int page = 1,
    int limit = Variables.defaultLimit,
    String? categoryId,
    String? search,
  }) async {
    try {
      final authData = await AuthLocalDataSource().getAuthData();
      final url = '${Variables.baseUrl}/api/v1/products';

      Map<String, dynamic> queryParameters = {
        'page': page,
        'limit': limit,
      };

      if (categoryId != null) {
        queryParameters['category_id'] = categoryId;
      }

      if (search != null && search.isNotEmpty) {
        queryParameters['search'] = search;
      }

      final response = await dio.get(
        url,
        queryParameters: queryParameters,
        options: Options(
          headers: {
            'Authorization': 'Bearer ${authData.token}',
            'Accept': 'application/json',
          },
        ),
      );

      if (response.statusCode == 200) {
        return Right(ProductResponseModel.fromMap(response.data));
      } else {
        return const Left('Failed to get products');
      }
    } on DioException catch (e) {
      log("Dio error: ${e.message}");
      return Left(e.response?.data['message'] ?? 'Gagal mengambil produk');
    } catch (e) {
      log("Unexpected error: $e", name: "productRemoteDatasource");
      return const Left('Unexpected error occurred');
    }
  }

  Future<Either<String, AddProductResponseModel>> addProduct(
      ProductRequestModel productRequestModel) async {
    try {
      final authData = await AuthLocalDataSource().getAuthData();
      final url = '${Variables.baseUrl}/api/v1/products';

      final response = await dio.post(
        url,
        data: productRequestModel.toMap(),
        options: Options(
          headers: {
            'Authorization': 'Bearer ${authData.token}',
            'Accept': 'application/json',
          },
        ),
      );

      if (response.statusCode == 200) {
        return Right(AddProductResponseModel.fromMap(response.data));
      } else {
        return const Left('Failed to create products');
      }
    } on DioException catch (e) {
      log("Dio error: ${e.message}");
      return Left(e.response?.data['message'] ?? 'Gagal menambah produk');
    } catch (e) {
      log("Unexpected error: $e");
      return const Left('Unexpected error occurred');
    }
  }

  Future<Either<String, AddProductResponseModel>> updateProduct(
      ProductRequestModel productRequestModel) async {
    try {
      final authData = await AuthLocalDataSource().getAuthData();
      final url =
          '${Variables.baseUrl}/api/v1/products/${productRequestModel.id}';

      final response = await dio.put(
        url,
        data: productRequestModel.toMap(),
        options: Options(
          headers: {
            'Authorization': 'Bearer ${authData.token}',
            'Accept': 'application/json',
          },
        ),
      );

      if (response.statusCode == 200) {
        return Right(AddProductResponseModel.fromMap(response.data));
      } else {
        return const Left('Failed to update products');
      }
    } on DioException catch (e) {
      log("Dio error: ${e.message}");
      return Left(e.response?.data['message'] ?? 'Gagal update produk');
    } catch (e) {
      log("Unexpected error: $e");
      return const Left('Unexpected error occurred');
    }
  }
}
