import 'dart:io';
import 'package:dio/dio.dart';
import '../../core/error/exceptions.dart';
import '../../core/network/api_client.dart';
import '../dto/attendance_response_dto.dart';

abstract class AttendanceRemoteDataSource {
  Future<AttendanceResponseDto> login({
    required String employeeId,
    required File faceImage,
  });

  Future<AttendanceResponseDto> logout({
    required String employeeId,
    required File faceImage,
  });
}

class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
  final ApiClient apiClient;

  AttendanceRemoteDataSourceImpl({required this.apiClient});
  @override
  Future<AttendanceResponseDto> login({
    required String employeeId,
    required File faceImage,
  }) async {
    try {
      final formData = FormData.fromMap({
        'EmployeeId': employeeId,
        'FaceImage': await MultipartFile.fromFile(faceImage.path),
      });

      final response = await apiClient.post(
        '/Attendance/login',
        data: formData,
        options: Options(contentType: 'multipart/form-data'),
      );

      if (response.statusCode == 200 || response.statusCode == 201) {
        final responseData = response.data;

        if (responseData is Map<String, dynamic>) {
          return AttendanceResponseDto.fromJson(responseData);
        } else {
          throw ServerException(
            message: 'استجابة غير صحيحة من الخادم',
            statusCode: response.statusCode,
          );
        }
      } else {
        throw ServerException(
          message: 'فشل تسجيل الدخول',
          statusCode: response.statusCode,
        );
      }
    } on DioException catch (e) {
      if (e.type == DioExceptionType.connectionTimeout ||
          e.type == DioExceptionType.receiveTimeout) {
        throw NetworkException(message: 'انتهت مهلة الاتصال');
      } else if (e.type == DioExceptionType.connectionError) {
        throw NetworkException(message: 'لا يوجد اتصال بالانترنيت');
      } else if (e.response?.statusCode == 500) {
        throw ServerException(message: 'خطأ في الخادم يرجى المحاولة لاحقا');
      } else if (e.response != null) {
        final message =
            e.response?.data?['message'] ??
            e.response?.data?['error'] ??
            'فشل تسجيل الدخول';

        throw ServerException(
          message: message.toString(),
          statusCode: e.response?.statusCode,
        );
      } else {
        throw NetworkException(message: 'خطأ في الانترنيت يرجى المحاولة لاحقا');
      }
    } catch (e) {
      if (e is ServerException || e is NetworkException) {
        rethrow;
      }
      print('خطأ غير متوقع: $e');
      throw ServerException(message: 'خطأ غير متوقع');
    }
  }

  @override
  Future<AttendanceResponseDto> logout({
    required String employeeId,
    required File faceImage,
  }) async {
    try {
      final formData = FormData.fromMap({
        'EmployeeId': employeeId,
        'FaceImage': await MultipartFile.fromFile(faceImage.path),
      });

      final response = await apiClient.post(
        '/Attendance/logout',
        data: formData,
        options: Options(contentType: 'multipart/form-data'),
      );

      if (response.statusCode == 200 || response.statusCode == 201) {
        final responseData = response.data;

        if (responseData is Map<String, dynamic>) {
          return AttendanceResponseDto.fromJson(responseData);
        } else {
          throw ServerException(
            message: 'استجابة غير صحيحة من الخادم',
            statusCode: response.statusCode,
          );
        }
      } else {
        throw ServerException(
          message: 'فشل تسجيل الخروج',
          statusCode: response.statusCode,
        );
      }
    } on DioException catch (e) {
      if (e.type == DioExceptionType.connectionTimeout ||
          e.type == DioExceptionType.receiveTimeout) {
        throw NetworkException(message: 'انتهت مهلة الاتصال');
      } else if (e.type == DioExceptionType.connectionError) {
        throw NetworkException(message: 'لا يوجد اتصال بالانترنيت');
      } else if (e.response?.statusCode == 500) {
        throw ServerException(message: 'خطأ في الخادم يرجى المحاولة لاحقا');
      } else if (e.response != null) {
        final message =
            e.response?.data?['message'] ??
            e.response?.data?['error'] ??
            'فشل تسجيل الخروج';

        throw ServerException(
          message: message.toString(),
          statusCode: e.response?.statusCode,
        );
      } else {
        throw NetworkException(message: 'خطأ في الانترنيت يرجى المحاولة لاحقا');
      }
    } catch (e) {
      if (e is ServerException || e is NetworkException) {
        rethrow;
      }
      throw ServerException(message: 'خطأ غير متوقع');
    }
  }
}
