import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import '../../core/constants/api_endpoints.dart';
import '../../core/errors/exceptions.dart';
import '../../domain/repositories/rent_repository.dart';
import '../models/rent_dto.dart';

@LazySingleton(as: RentRepository)
class RentRepositoryImpl implements RentRepository {
  final Dio dio;

  RentRepositoryImpl(this.dio);

  @override
  Future<RentListResponse> getRents({
    int page = 1,
    int pageSize = 10,
    String? search,
    String? status,
    int? equipmentHistoryId,
  }) async {
    try {
      final queryParameters = <String, dynamic>{
        'page': page,
        'page_size': pageSize,
      };
      
      if (search != null && search.isNotEmpty) {
        queryParameters['search'] = search;
      }
      
      if (status != null && status.isNotEmpty) {
        queryParameters['status'] = status;
      }
      
      if (equipmentHistoryId != null) {
        queryParameters['equipment_history_id'] = equipmentHistoryId;
      }

      final response = await dio.get(
        ApiEndpoints.rents,
        queryParameters: queryParameters,
      );

      return RentListResponse.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException(message: _handleError(e));
    } catch (e) {
      throw ServerException(message: '임대 목록을 가져오는 중 오류가 발생했습니다: $e');
    }
  }

  @override
  Future<RentDto> getRent(int id) async {
    try {
      final response = await dio.get('${ApiEndpoints.rents}/$id');
      return RentDto.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException(message: _handleError(e));
    } catch (e) {
      throw ServerException(message: '임대 상세 정보를 가져오는 중 오류가 발생했습니다: $e');
    }
  }

  @override
  Future<RentDto> createRent(RentRequestDto request) async {
    try {
      final response = await dio.post(
        ApiEndpoints.rents,
        data: request.toJson(),
      );
      return RentDto.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException(message: _handleError(e));
    } catch (e) {
      throw ServerException(message: '임대 생성 중 오류가 발생했습니다: $e');
    }
  }

  @override
  Future<RentDto> updateRent(int id, RentUpdateRequestDto request) async {
    try {
      final response = await dio.put(
        '${ApiEndpoints.rents}/$id',
        data: request.toJson(),
      );
      return RentDto.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException(message: _handleError(e));
    } catch (e) {
      throw ServerException(message: '임대 수정 중 오류가 발생했습니다: $e');
    }
  }

  @override
  Future<void> deleteRent(int id) async {
    try {
      await dio.delete('${ApiEndpoints.rents}/$id');
    } on DioException catch (e) {
      throw ServerException(message: _handleError(e));
    } catch (e) {
      throw ServerException(message: '임대 삭제 중 오류가 발생했습니다: $e');
    }
  }

  @override
  Future<RentListResponse> getActiveRents({
    int page = 1,
    int pageSize = 10,
  }) async {
    try {
      final response = await dio.get(
        ApiEndpoints.rentsActive,
        queryParameters: {
          'page': page,
          'page_size': pageSize,
        },
      );
      return RentListResponse.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException(message: _handleError(e));
    } catch (e) {
      throw ServerException(message: '진행 중인 임대 목록을 가져오는 중 오류가 발생했습니다: $e');
    }
  }

  @override
  Future<RentListResponse> getOverdueRents({
    int page = 1,
    int pageSize = 10,
  }) async {
    try {
      final response = await dio.get(
        ApiEndpoints.rentsOverdue,
        queryParameters: {
          'page': page,
          'page_size': pageSize,
        },
      );
      return RentListResponse.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException(message: _handleError(e));
    } catch (e) {
      throw ServerException(message: '연체된 임대 목록을 가져오는 중 오류가 발생했습니다: $e');
    }
  }

  @override
  Future<Map<String, dynamic>> getRentStats() async {
    try {
      final response = await dio.get(ApiEndpoints.rentsStats);
      return response.data as Map<String, dynamic>;
    } on DioException catch (e) {
      throw ServerException(message: _handleError(e));
    } catch (e) {
      throw ServerException(message: '임대 통계를 가져오는 중 오류가 발생했습니다: $e');
    }
  }

  @override
  Future<RentDto> returnRent(int id, String returnDate) async {
    try {
      final response = await dio.put(
        '${ApiEndpoints.rents}/$id',
        data: {
          'actual_return_date': returnDate,
          'status': 'returned',
        },
      );
      return RentDto.fromJson(response.data);
    } on DioException catch (e) {
      throw ServerException(message: _handleError(e));
    } catch (e) {
      throw ServerException(message: '장비 반납 처리 중 오류가 발생했습니다: $e');
    }
  }

  // 에러 처리 메서드
  String _handleError(DioException e) {
    if (e.response != null) {
      final statusCode = e.response!.statusCode;
      final data = e.response!.data;
      
      if (data is Map && data.containsKey('message')) {
        return data['message'];
      }
      
      switch (statusCode) {
        case 400:
          return '잘못된 요청입니다.';
        case 401:
          return '인증이 필요합니다.';
        case 403:
          return '권한이 없습니다.';
        case 404:
          return '리소스를 찾을 수 없습니다.';
        case 500:
          return '서버 내부 오류입니다.';
        default:
          return 'HTTP 오류 $statusCode';
      }
    }
    
    switch (e.type) {
      case DioExceptionType.connectionTimeout:
        return '연결 시간 초과';
      case DioExceptionType.sendTimeout:
        return '요청 전송 시간 초과';
      case DioExceptionType.receiveTimeout:
        return '응답 수신 시간 초과';
      case DioExceptionType.connectionError:
        return '네트워크 연결 오류';
      case DioExceptionType.cancel:
        return '요청이 취소됨';
      default:
        return '네트워크 오류: ${e.message}';
    }
  }
}