import 'package:get_it/get_it.dart';
import 'package:superport/models/warehouse_location_model.dart';
import 'package:superport/services/warehouse_service.dart';
import 'package:superport/core/utils/error_handler.dart';
import 'package:superport/core/controllers/base_list_controller.dart';
import 'package:superport/data/models/common/pagination_params.dart';

/// 입고지 리스트 상태 및 CRUD만 담당하는 컨트롤러 클래스 (리팩토링 버전)
/// BaseListController를 상속받아 공통 기능을 재사용
class WarehouseLocationListController extends BaseListController<WarehouseLocation> {
  late final WarehouseService _warehouseService;
  
  // 필터 옵션
  bool? _isActive;
  bool _includeInactive = false; // 비활성 창고 포함 여부

  WarehouseLocationListController() {
    if (GetIt.instance.isRegistered<WarehouseService>()) {
      _warehouseService = GetIt.instance<WarehouseService>();
    } else {
      throw Exception('WarehouseService not registered in GetIt');
    }
  }

  // 추가 Getters
  List<WarehouseLocation> get warehouseLocations => items;
  bool? get isActive => _isActive;
  bool get includeInactive => _includeInactive;
  
  // 비활성 포함 토글
  void toggleIncludeInactive() {
    _includeInactive = !_includeInactive;
    loadData(isRefresh: true);
  }

  @override
  Future<PagedResult<WarehouseLocation>> fetchData({
    required PaginationParams params,
    Map<String, dynamic>? additionalFilters,
  }) async {
    // API 사용 (PaginatedResponse 반환)
    final response = await ErrorHandler.handleApiCall(
      () => _warehouseService.getWarehouseLocations(
        page: params.page,
        perPage: params.perPage,
        isActive: _isActive,
        search: params.search,
        includeInactive: _includeInactive,
      ),
      onError: (failure) {
        throw failure;
      },
    );
    
    if (response == null) {
      return PagedResult(
        items: [],
        meta: PaginationMeta(
          currentPage: params.page,
          perPage: params.perPage,
          total: 0,
          totalPages: 0,
          hasNext: false,
          hasPrevious: false,
        ),
      );
    }
    
    // PaginatedResponse를 PagedResult로 변환
    final meta = PaginationMeta(
      currentPage: response.page,
      perPage: response.size,
      total: response.totalElements,
      totalPages: response.totalPages,
      hasNext: !response.last,
      hasPrevious: !response.first,
    );
    
    return PagedResult(items: response.items, meta: meta);
  }

  @override
  bool filterItem(WarehouseLocation item, String query) {
    return item.name.toLowerCase().contains(query.toLowerCase()) ||
           item.address.toString().toLowerCase().contains(query.toLowerCase());
  }
  
  /// 데이터 로드 (호환성을 위해 유지)
  Future<void> loadWarehouseLocations({bool isInitialLoad = true}) async {
    await loadData(isRefresh: isInitialLoad);
  }

  // 필터 설정
  void setFilters({bool? isActive}) {
    _isActive = isActive;
    loadData(isRefresh: true);
  }

  /// 창고 위치 상세 데이터 로드
  Future<WarehouseLocation?> loadWarehouseDetail(int warehouseId) async {
    try {
      final location = await _warehouseService.getWarehouseLocationById(warehouseId);
      return location;
    } catch (e) {
      print('Failed to load warehouse detail: $e');
      return null;
    }
  }

  // 필터 초기화
  void clearFilters() {
    _isActive = null;
    search('');
    loadData(isRefresh: true);
  }

  /// 입고지 추가
  Future<void> addWarehouseLocation(WarehouseLocation location) async {
    await ErrorHandler.handleApiCall<void>(
      () => _warehouseService.createWarehouseLocation(location),
      onError: (failure) {
        throw failure;
      },
    );
    
    // 목록 새로고침
    await refresh();
  }

  /// 입고지 수정
  Future<void> updateWarehouseLocation(WarehouseLocation location) async {
    await ErrorHandler.handleApiCall<void>(
      () => _warehouseService.updateWarehouseLocation(location),
      onError: (failure) {
        throw failure;
      },
    );
    
    // 로컬 업데이트
    updateItemLocally(location, (l) => l.id == location.id);
  }

  /// 입고지 삭제
  Future<void> deleteWarehouseLocation(int id) async {
    await ErrorHandler.handleApiCall<void>(
      () => _warehouseService.deleteWarehouseLocation(id),
      onError: (failure) {
        throw failure;
      },
    );
    
    // 로컬 삭제 대신 서버에서 새로고침
    // removeItemLocally((l) => l.id == id);
    
    // 삭제 후 리스트 새로고침 (서버에서 10개 다시 가져오기)
    await refresh();
  }

  // 사용 중인 창고 위치 조회
  Future<List<WarehouseLocation>> getInUseWarehouseLocations() async {
    final locations = await ErrorHandler.handleApiCall<List<WarehouseLocation>>(
      () => _warehouseService.getInUseWarehouseLocations(),
      onError: (failure) {
        throw failure;
      },
    );
    return locations ?? [];
  }
  
}