import 'package:dio/dio.dart';
import '../models/maintenance_dto.dart';
import '../../utils/constants.dart';

class MaintenanceRepository {
  final Dio _dio;
  static const String _baseEndpoint = '/maintenances';

  MaintenanceRepository({required Dio dio}) : _dio = dio;

  // 유지보수 목록 조회
  Future<MaintenanceListResponse> getMaintenances({
    int page = 1,
    int pageSize = PaginationConstants.defaultPageSize,
    String? sortBy,
    String? sortOrder,
    String? search,
    int? equipmentHistoryId,
    String? maintenanceType,
    String? status, // MaintenanceStatus enum 제거, String으로 단순화
  }) async {
    try {
      final queryParams = {
        'page': page,
        'page_size': pageSize,
        if (sortBy != null) 'sort_by': sortBy,
        if (sortOrder != null) 'sort_order': sortOrder,
        if (search != null) 'search': search,
        if (equipmentHistoryId != null) 'equipment_history_id': equipmentHistoryId,
        if (maintenanceType != null) 'maintenance_type': maintenanceType,
        if (status != null) 'status': status,
      };

      final response = await _dio.get(
        _baseEndpoint,
        queryParameters: queryParams,
      );

      return MaintenanceListResponse.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // 특정 유지보수 조회
  Future<MaintenanceDto> getMaintenance(int id) async {
    try {
      final response = await _dio.get('$_baseEndpoint/$id');
      return MaintenanceDto.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // 장비 이력별 유지보수 조회
  Future<List<MaintenanceDto>> getMaintenancesByEquipmentHistory(int equipmentHistoryId) async {
    try {
      final response = await _dio.get(
        _baseEndpoint,
        queryParameters: {'equipment_history_id': equipmentHistoryId},
      );

      final data = response.data;
      if (data is Map && data.containsKey('maintenances')) {
        return (data['maintenances'] as List)
            .map((json) => MaintenanceDto.fromJson(json))
            .toList();
      }
      return (data as List).map((json) => MaintenanceDto.fromJson(json)).toList();
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // 만료 예정 유지보수 조회
  Future<List<MaintenanceDto>> getUpcomingMaintenances({
    int daysAhead = 30,
  }) async {
    try {
      final response = await _dio.get(
        '$_baseEndpoint/upcoming',
        queryParameters: {'days_ahead': daysAhead},
      );

      final data = response.data;
      if (data is Map && data.containsKey('maintenances')) {
        return (data['maintenances'] as List)
            .map((json) => MaintenanceDto.fromJson(json))
            .toList();
      }
      return (data as List).map((json) => MaintenanceDto.fromJson(json)).toList();
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // 만료된 유지보수 조회
  Future<List<MaintenanceDto>> getOverdueMaintenances() async {
    try {
      final response = await _dio.get('$_baseEndpoint/overdue');

      final data = response.data;
      if (data is Map && data.containsKey('maintenances')) {
        return (data['maintenances'] as List)
            .map((json) => MaintenanceDto.fromJson(json))
            .toList();
      }
      return (data as List).map((json) => MaintenanceDto.fromJson(json)).toList();
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // 유지보수 생성
  Future<MaintenanceDto> createMaintenance(MaintenanceRequestDto request) async {
    try {
      final response = await _dio.post(
        _baseEndpoint,
        data: request.toJson(),
      );

      return MaintenanceDto.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // 유지보수 수정
  Future<MaintenanceDto> updateMaintenance(int id, MaintenanceUpdateRequestDto request) async {
    try {
      final response = await _dio.put(
        '$_baseEndpoint/$id',
        data: request.toJson(),
      );

      return MaintenanceDto.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // 유지보수 삭제
  Future<void> deleteMaintenance(int id) async {
    try {
      await _dio.delete('$_baseEndpoint/$id');
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // 유지보수 상태 변경 (활성/비활성)
  Future<MaintenanceDto> toggleMaintenanceStatus(int id, bool isActive) async {
    try {
      final response = await _dio.patch(
        '$_baseEndpoint/$id/status',
        data: {'is_active': isActive},
      );

      return MaintenanceDto.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // 다음 유지보수 날짜 계산
  Future<String> calculateNextMaintenanceDate(int id) async {
    try {
      final response = await _dio.post(
        '$_baseEndpoint/$id/calculate-next-date',
      );

      return response.data['next_maintenance_date'];
    } on DioException catch (e) {
      throw _handleError(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 409:
          return '중복된 유지보수 정보가 존재합니다.';
        case 500:
          return '서버 오류가 발생했습니다.';
        default:
          return '오류가 발생했습니다. (코드: $statusCode)';
      }
    }
    
    if (e.type == DioExceptionType.connectionTimeout) {
      return '연결 시간이 초과되었습니다.';
    } else if (e.type == DioExceptionType.connectionError) {
      return '네트워크 연결을 확인해주세요.';
    }
    
    return '알 수 없는 오류가 발생했습니다.';
  }
}