import 'dart:developer';

import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart';
import 'package:enaklo_pos/core/constants/variables.dart';
import 'package:enaklo_pos/core/network/dio_client.dart';
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
import 'package:enaklo_pos/data/models/response/dashboard_analytic_response_model.dart';
import 'package:enaklo_pos/data/models/response/payment_method_analytic_response_model.dart';
import 'package:enaklo_pos/data/models/response/product_analytic_response_model.dart';
import 'package:enaklo_pos/data/models/response/profit_loss_response_model.dart';
import 'package:enaklo_pos/data/models/response/sales_analytic_response_model.dart';
import 'package:intl/intl.dart';

class AnalyticRemoteDatasource {
  final Dio dio = DioClient.instance;

  Future<Either<String, PaymentMethodAnalyticResponseModel>> getPaymentMethod({
    required DateTime dateFrom,
    required DateTime dateTo,
  }) async {
    final authData = await AuthLocalDataSource().getAuthData();
    final headers = {
      'Authorization': 'Bearer ${authData.token}',
      'Accept': 'application/json',
    };

    try {
      final response = await dio.get(
        '${Variables.baseUrl}/api/v1/analytics/payment-methods',
        queryParameters: {
          'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
          'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
        },
        options: Options(headers: headers),
      );

      if (response.statusCode == 200) {
        return right(PaymentMethodAnalyticResponseModel.fromMap(response.data));
      } else {
        return left('Terjadi Kesalahan, Coba lagi nanti.');
      }
    } on DioException catch (e) {
      log('Dio error: ${e.message}');
      return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
    } catch (e) {
      log('Unexpected error: $e');
      return left('Unexpected error occurred');
    }
  }

  Future<Either<String, SalesAnalyticResponseModel>> getSales({
    required DateTime dateFrom,
    required DateTime dateTo,
  }) async {
    final authData = await AuthLocalDataSource().getAuthData();
    final headers = {
      'Authorization': 'Bearer ${authData.token}',
      'Accept': 'application/json',
    };

    try {
      final response = await dio.get(
        '${Variables.baseUrl}/api/v1/analytics/sales',
        queryParameters: {
          'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
          'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
        },
        options: Options(headers: headers),
      );

      if (response.statusCode == 200) {
        return right(SalesAnalyticResponseModel.fromMap(response.data));
      } else {
        return left('Terjadi Kesalahan, Coba lagi nanti.');
      }
    } on DioException catch (e) {
      log('Dio error: ${e.message}');
      return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
    } catch (e) {
      log('Unexpected error: $e');
      return left('Unexpected error occurred');
    }
  }

  Future<Either<String, ProductAnalyticResponseModel>> getProduct({
    required DateTime dateFrom,
    required DateTime dateTo,
  }) async {
    final authData = await AuthLocalDataSource().getAuthData();
    final headers = {
      'Authorization': 'Bearer ${authData.token}',
      'Accept': 'application/json',
    };

    try {
      final response = await dio.get(
        '${Variables.baseUrl}/api/v1/analytics/products',
        queryParameters: {
          'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
          'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
        },
        options: Options(headers: headers),
      );

      if (response.statusCode == 200) {
        return right(ProductAnalyticResponseModel.fromMap(response.data));
      } else {
        return left('Terjadi Kesalahan, Coba lagi nanti.');
      }
    } on DioException catch (e) {
      log('Dio error: ${e.message}');
      return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
    } catch (e) {
      log('Unexpected error: $e');
      return left('Unexpected error occurred');
    }
  }

  Future<Either<String, DashboardAnalyticResponseModel>> getDashboard({
    required DateTime dateFrom,
    required DateTime dateTo,
  }) async {
    final authData = await AuthLocalDataSource().getAuthData();
    final headers = {
      'Authorization': 'Bearer ${authData.token}',
      'Accept': 'application/json',
    };

    try {
      final response = await dio.get(
        '${Variables.baseUrl}/api/v1/analytics/dashboard',
        queryParameters: {
          'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
          'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
        },
        options: Options(headers: headers),
      );

      if (response.statusCode == 200) {
        return right(DashboardAnalyticResponseModel.fromMap(response.data));
      } else {
        return left('Terjadi Kesalahan, Coba lagi nanti.');
      }
    } on DioException catch (e) {
      log('Dio error: ${e.message}');
      return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
    } catch (e) {
      log('Unexpected error: $e');
      return left('Unexpected error occurred');
    }
  }

  Future<Either<String, ProfitLossResponseModel>> getProfitLoss({
    required DateTime dateFrom,
    required DateTime dateTo,
  }) async {
    final authData = await AuthLocalDataSource().getAuthData();
    final headers = {
      'Authorization': 'Bearer ${authData.token}',
      'Accept': 'application/json',
    };

    try {
      final response = await dio.get(
        '${Variables.baseUrl}/api/v1/analytics/profit-loss',
        queryParameters: {
          'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
          'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
        },
        options: Options(headers: headers),
      );

      if (response.statusCode == 200) {
        return right(ProfitLossResponseModel.fromMap(response.data));
      } else {
        return left('Terjadi Kesalahan, Coba lagi nanti.');
      }
    } on DioException catch (e) {
      log('Dio error: ${e.message}');
      return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
    } catch (e) {
      log('Unexpected error: $e');
      return left('Unexpected error occurred');
    }
  }
}
