import 'package:flutter/foundation.dart';
import 'package:injectable/injectable.dart';
import 'package:superport/core/constants/api_endpoints.dart';
import 'package:superport/core/errors/exceptions.dart';
import 'package:superport/data/datasources/remote/api_client.dart';
import 'package:superport/data/models/warehouse/warehouse_dto.dart';

abstract class WarehouseLocationRemoteDataSource {
  Future<WarehouseLocationListDto> getWarehouseLocations({
    int page = 1,
    int perPage = 20,
    String? search,
    Map<String, dynamic>? filters,
  });

  Future<WarehouseDto> getWarehouseLocationDetail(int id);
  Future<WarehouseDto> createWarehouseLocation(WarehouseRequestDto request);
  Future<WarehouseDto> updateWarehouseLocation(int id, WarehouseUpdateRequestDto request);
  Future<void> deleteWarehouseLocation(int id);
  Future<WarehouseCapacityInfo> getWarehouseCapacity(int id);
  Future<WarehouseEquipmentListDto> getWarehouseEquipment({
    required int warehouseId,
    int page = 1,
    int perPage = 20,
  });
  
  // Repository에서 사용하는 추가 메서드들
  Future<void> updateWarehouseLocationStatus(int id, bool isActive);
  Future<bool> checkWarehouseHasEquipment(int id);
  Future<bool> checkDuplicateWarehouseName(String name);
}

@LazySingleton(as: WarehouseLocationRemoteDataSource)
class WarehouseLocationRemoteDataSourceImpl implements WarehouseLocationRemoteDataSource {
  final ApiClient _apiClient;

  WarehouseLocationRemoteDataSourceImpl({
    required ApiClient apiClient,
  }) : _apiClient = apiClient;

  @override
  Future<WarehouseLocationListDto> getWarehouseLocations({
    int page = 1,
    int perPage = 20,
    String? search,
    Map<String, dynamic>? filters,
  }) async {
    try {
      final queryParams = <String, dynamic>{
        'page': page,
        'per_page': perPage,
      };

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

      // 필터 적용
      if (filters != null) {
        filters.forEach((key, value) {
          if (value != null) {
            queryParams[key] = value;
          }
        });
      }

      final response = await _apiClient.get(
        ApiEndpoints.warehouses,
        queryParameters: queryParams,
      );

      if (response.data != null) {
        // 백엔드는 직접 페이지네이션 구조를 반환
        final data = response.data['data'];
        if (data != null && data is List) {
          final List<WarehouseDto> warehouses = [];
          
          for (int i = 0; i < data.length; i++) {
            try {
              final item = data[i];
              debugPrint('📦 Parsing warehouse location item $i: ${item['name']}');
              
              final warehouseDto = WarehouseDto.fromJson(item);
              warehouses.add(warehouseDto);
            } catch (e, stackTrace) {
              debugPrint('❌ Error parsing warehouse location item $i: $e');
              debugPrint('Item data: ${data[i]}');
              debugPrint('Stack trace: $stackTrace');
              continue;
            }
          }
          
          return WarehouseLocationListDto(
            items: warehouses,
            total: response.data['total'] ?? warehouses.length,
            page: response.data['page'] ?? page,
            perPage: response.data['page_size'] ?? perPage,
            totalPages: response.data['total_pages'] ?? 1,
          );
        } else {
          throw ApiException(
            message: 'Invalid response format: expected data array',
          );
        }
      } else {
        throw ApiException(
          message: 'Empty response from server',
        );
      }
    } catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<WarehouseDto> getWarehouseLocationDetail(int id) async {
    try {
      final response = await _apiClient.get(
        '${ApiEndpoints.warehouses}/$id',
      );

      if (response.data != null) {
        return WarehouseDto.fromJson(response.data);
      } else {
        throw ApiException(
          message: 'Failed to fetch warehouse location',
        );
      }
    } catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<WarehouseDto> createWarehouseLocation(WarehouseRequestDto request) async {
    try {
      final response = await _apiClient.post(
        ApiEndpoints.warehouses,
        data: request.toJson(),
      );

      if (response.data != null) {
        return WarehouseDto.fromJson(response.data);
      } else {
        throw ApiException(
          message: 'Failed to create warehouse location',
        );
      }
    } catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<WarehouseDto> updateWarehouseLocation(int id, WarehouseUpdateRequestDto request) async {
    try {
      final response = await _apiClient.put(
        '${ApiEndpoints.warehouses}/$id',
        data: request.toJson(),
      );

      if (response.data != null) {
        return WarehouseDto.fromJson(response.data);
      } else {
        throw ApiException(
          message: 'Failed to update warehouse location',
        );
      }
    } catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<void> deleteWarehouseLocation(int id) async {
    try {
      await _apiClient.delete(
        '${ApiEndpoints.warehouses}/$id',
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<WarehouseCapacityInfo> getWarehouseCapacity(int id) async {
    try {
      final response = await _apiClient.get(
        '${ApiEndpoints.warehouses}/$id/capacity',
      );

      if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
        return WarehouseCapacityInfo.fromJson(response.data['data']);
      } else {
        throw ApiException(
          message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse capacity',
        );
      }
    } catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<WarehouseEquipmentListDto> getWarehouseEquipment({
    required int warehouseId,
    int page = 1,
    int perPage = 20,
  }) async {
    try {
      final queryParams = <String, dynamic>{
        'page': page,
        'per_page': perPage,
      };

      final response = await _apiClient.get(
        '${ApiEndpoints.warehouses}/$warehouseId/equipment',
        queryParameters: queryParams,
      );

      if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
        final data = response.data['data'];
        final pagination = response.data['pagination'] ?? {};
        
        if (data is List) {
          // 배열 응답을 WarehouseEquipmentListDto 형식으로 변환
          final List<WarehouseEquipmentDto> equipment = [];
          
          for (var item in data) {
            try {
              equipment.add(WarehouseEquipmentDto.fromJson(item));
            } catch (e) {
              debugPrint('❌ Error parsing warehouse equipment: $e');
              debugPrint('Item data: $item');
              continue;
            }
          }
          
          return WarehouseEquipmentListDto(
            items: equipment,
            total: pagination['total'] ?? equipment.length,
          );
        } else {
          // 이미 올바른 형식인 경우
          return WarehouseEquipmentListDto.fromJson(data);
        }
      } else {
        throw ApiException(
          message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse equipment',
        );
      }
    } catch (e) {
      throw _handleError(e);
    }
  }

  // Repository에서 사용하는 추가 메서드들 구현
  @override
  Future<void> updateWarehouseLocationStatus(int id, bool isActive) async {
    try {
      await _apiClient.patch(
        '${ApiEndpoints.warehouses}/$id/status',
        data: {'is_active': isActive},
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<bool> checkWarehouseHasEquipment(int id) async {
    try {
      final response = await _apiClient.get(
        '${ApiEndpoints.warehouses}/$id/has-equipment',
      );
      
      if (response.data != null && response.data['success'] == true) {
        return response.data['data']['has_equipment'] ?? false;
      }
      return false;
    } catch (e) {
      // 오류 시 기본값 false 반환
      debugPrint('📦 창고 장비 보유 여부 확인 중 오류: $e');
      return false;
    }
  }

  @override
  Future<bool> checkDuplicateWarehouseName(String name) async {
    try {
      final response = await _apiClient.get(
        '${ApiEndpoints.warehouses}/check-duplicate',
        queryParameters: {'name': name},
      );
      
      if (response.data != null && response.data['success'] == true) {
        return response.data['data']['is_duplicate'] ?? false;
      }
      return false;
    } catch (e) {
      // 오류 시 기본값 false 반환 (중복이 아니라고 가정)
      debugPrint('📦 중복 창고명 확인 중 오류: $e');
      return false;
    }
  }

  Exception _handleError(dynamic error) {
    if (error is ApiException) {
      return error;
    }
    return ApiException(
      message: error.toString(),
    );
  }
}