import 'package:flutter/foundation.dart';
import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'package:superport/core/constants/app_constants.dart';
import 'package:superport/core/errors/exceptions.dart';
import 'package:superport/core/errors/failures.dart';
import 'package:superport/data/datasources/remote/warehouse_remote_datasource.dart';
import 'package:superport/data/models/common/paginated_response.dart';
import 'package:superport/data/models/warehouse/warehouse_dto.dart';
import 'package:superport/models/warehouse_location_model.dart';

@lazySingleton
class WarehouseService {
  final WarehouseRemoteDataSource _remoteDataSource = GetIt.instance<WarehouseRemoteDataSource>();

  // 창고 위치 목록 조회
  Future<PaginatedResponse<WarehouseLocation>> getWarehouseLocations({
    int page = 1,
    int perPage = AppConstants.warehousePageSize,
    bool? isActive,
    String? search,
    bool includeInactive = false,
  }) async {
    try {
      final response = await _remoteDataSource.getWarehouseLocations(
        page: page,
        perPage: perPage,
        isActive: isActive,
        search: search,
        includeInactive: includeInactive,
      );

      return PaginatedResponse<WarehouseLocation>(
        items: response.items.map((dto) => _convertDtoToWarehouseLocation(dto)).toList(),
        page: response.page,
        size: response.perPage,
        totalElements: response.total,
        totalPages: response.totalPages,
        first: response.page == 1,
        last: response.page >= response.totalPages,
      );
    } on ApiException catch (e) {
      debugPrint('[WarehouseService] ApiException: ${e.message}');
      throw ServerFailure(message: e.message);
    } catch (e, stackTrace) {
      debugPrint('[WarehouseService] Error loading warehouse locations: $e');
      debugPrint('[WarehouseService] Stack trace: $stackTrace');
      throw ServerFailure(message: '창고 위치 목록을 불러오는 데 실패했습니다: $e');
    }
  }

  // 창고 위치 상세 조회
  Future<WarehouseLocation> getWarehouseLocationById(int id) async {
    try {
      final dto = await _remoteDataSource.getWarehouseLocationById(id);
      return _convertDtoToWarehouseLocation(dto);
    } on ApiException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: '창고 위치 정보를 불러오는 데 실패했습니다: $e');
    }
  }

  // 창고 위치 생성
  Future<WarehouseLocation> createWarehouseLocation(WarehouseLocation location) async {
    try {
      final request = WarehouseRequestDto(
        name: location.name,
        zipcodesZipcode: location.zipcode, // 우편번호 전달
        remark: location.remark,
      );

      final dto = await _remoteDataSource.createWarehouseLocation(request);
      return _convertDtoToWarehouseLocation(dto);
    } on ApiException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: '창고 위치 생성에 실패했습니다: $e');
    }
  }

  // 창고 위치 수정
  Future<WarehouseLocation> updateWarehouseLocation(WarehouseLocation location) async {
    try {
      final request = WarehouseUpdateRequestDto(
        name: location.name,
        zipcodesZipcode: location.zipcode, // 우편번호 전달
        remark: location.remark,
      );

      final dto = await _remoteDataSource.updateWarehouseLocation(location.id, request);
      return _convertDtoToWarehouseLocation(dto);
    } on ApiException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: '창고 위치 수정에 실패했습니다: $e');
    }
  }

  // 창고 위치 삭제
  Future<void> deleteWarehouseLocation(int id) async {
    try {
      await _remoteDataSource.deleteWarehouseLocation(id);
    } on ApiException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: '창고 위치 삭제에 실패했습니다: $e');
    }
  }

  // 창고별 장비 목록 조회
  Future<List<Map<String, dynamic>>> getWarehouseEquipment(
    int warehouseId, {
    int page = 1,
    int perPage = AppConstants.warehousePageSize,
  }) async {
    try {
      final response = await _remoteDataSource.getWarehouseEquipment(
        warehouseId,
        page: page,
        perPage: perPage,
      );

      return response.items.map((dto) => {
        'id': dto.id,
        'equipmentId': dto.equipmentId,
        'warehouseId': dto.warehouseId,
        'name': dto.name,
        'quantity': dto.quantity,
      }).toList();
    } on ApiException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: '창고 장비 목록을 불러오는 데 실패했습니다: $e');
    }
  }

  // 창고 용량 정보 조회
  Future<WarehouseCapacityInfo> getWarehouseCapacity(int id) async {
    try {
      return await _remoteDataSource.getWarehouseCapacity(id);
    } on ApiException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: '창고 용량 정보를 불러오는 데 실패했습니다: $e');
    }
  }

  // 사용 중인 창고 위치 목록 조회
  Future<List<WarehouseLocation>> getInUseWarehouseLocations() async {
    try {
      final dtos = await _remoteDataSource.getInUseWarehouseLocations();
      return dtos.map((dto) => _convertDtoToWarehouseLocation(dto)).toList();
    } on ApiException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: '사용 중인 창고 위치를 불러오는 데 실패했습니다: $e');
    }
  }

  // DTO를 Flutter 모델로 변환 (백엔드 API 호환)
  WarehouseLocation _convertDtoToWarehouseLocation(WarehouseDto dto) {
    // 주소 조합: 우편번호와 주소를 함께 표시
    String? fullAddress;
    if (dto.zipcodeAddress != null) {
      if (dto.zipcodesZipcode != null) {
        fullAddress = '${dto.zipcodeAddress} (${dto.zipcodesZipcode})';
      } else {
        fullAddress = dto.zipcodeAddress;
      }
    } else {
      fullAddress = dto.zipcodesZipcode;
    }
    
    return WarehouseLocation(
      id: dto.id ?? 0,
      name: dto.name,
      address: fullAddress ?? '', // 우편번호와 주소를 조합
      managerName: '', // 백엔드에 없는 필드 - 빈 문자열
      managerPhone: '', // 백엔드에 없는 필드 - 빈 문자열  
      capacity: 0, // 백엔드에 없는 필드 - 기본값 0
      remark: dto.remark,
      isActive: !dto.isDeleted, // isDeleted의 반대가 isActive
      createdAt: dto.registeredAt ?? DateTime.now(), // registeredAt를 createdAt으로 매핑, null일 경우 현재 시간
    );
  }

  // 페이지네이션 정보
  Future<int> getTotalWarehouseLocations({bool? isActive}) async {
    try {
      final response = await _remoteDataSource.getWarehouseLocations(
        page: 1,
        perPage: 1,
        isActive: isActive,
      );
      return response.total;
    } catch (e) {
      return 0;
    }
  }
}