import 'package:flutter/material.dart';
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/services/mock_data_service.dart';
import 'package:superport/core/errors/failures.dart';

/// 입고지 리스트 상태 및 CRUD만 담당하는 컨트롤러 클래스 (SRP 적용)
/// UI, 네비게이션, 다이얼로그 등은 포함하지 않음
/// 향후 서비스/리포지토리 DI 구조로 확장 가능
class WarehouseLocationListController extends ChangeNotifier {
  final bool useApi;
  final MockDataService? mockDataService;
  WarehouseService? _warehouseService;
  
  List<WarehouseLocation> _warehouseLocations = [];
  List<WarehouseLocation> _filteredLocations = [];
  bool _isLoading = false;
  String? _error;
  String _searchQuery = '';
  int _currentPage = 1;
  final int _pageSize = 20;
  bool _hasMore = true;
  int _total = 0;

  // 필터 옵션
  bool? _isActive;

  WarehouseLocationListController({this.useApi = true, this.mockDataService}) {
    if (useApi && GetIt.instance.isRegistered<WarehouseService>()) {
      _warehouseService = GetIt.instance<WarehouseService>();
    }
  }

  // Getters
  List<WarehouseLocation> get warehouseLocations => _filteredLocations;
  bool get isLoading => _isLoading;
  String? get error => _error;
  String get searchQuery => _searchQuery;
  int get currentPage => _currentPage;
  bool get hasMore => _hasMore;
  int get total => _total;
  bool? get isActive => _isActive;

  /// 데이터 로드
  Future<void> loadWarehouseLocations({bool isInitialLoad = true}) async {
    if (_isLoading) return;

    print('[WarehouseLocationListController] loadWarehouseLocations started - isInitialLoad: $isInitialLoad');

    _isLoading = true;
    _error = null;
    
    if (isInitialLoad) {
      _currentPage = 1;
      _warehouseLocations.clear();
      _hasMore = true;
    } else {
      // 다음 페이지를 로드할 때는 페이지 번호를 먼저 증가
      _currentPage++;
    }
    
    notifyListeners();

    try {
      if (useApi && _warehouseService != null) {
        // API 사용
        print('[WarehouseLocationListController] Using API to fetch warehouse locations');
        final fetchedLocations = await _warehouseService!.getWarehouseLocations(
          page: _currentPage,
          perPage: _pageSize,
          isActive: _isActive,
        );

        print('[WarehouseLocationListController] API returned ${fetchedLocations.length} locations');

        if (isInitialLoad) {
          _warehouseLocations = fetchedLocations;
        } else {
          _warehouseLocations.addAll(fetchedLocations);
        }

        _hasMore = fetchedLocations.length >= _pageSize;
        
        // 전체 개수 조회
        _total = await _warehouseService!.getTotalWarehouseLocations(
          isActive: _isActive,
        );
        print('[WarehouseLocationListController] Total warehouse locations: $_total');
      } else {
        // Mock 데이터 사용
        print('[WarehouseLocationListController] Using Mock data');
        final allLocations = mockDataService?.getAllWarehouseLocations() ?? [];
        print('[WarehouseLocationListController] Mock data has ${allLocations.length} locations');
        
        // 필터링 적용
        var filtered = allLocations;
        if (_isActive != null) {
          // Mock 데이터에는 isActive 필드가 없으므로 모두 활성으로 처리
          filtered = _isActive! ? allLocations : [];
        }

        // 페이지네이션 적용
        final startIndex = (_currentPage - 1) * _pageSize;
        final endIndex = startIndex + _pageSize;
        
        if (startIndex < filtered.length) {
          final pageLocations = filtered.sublist(
            startIndex,
            endIndex > filtered.length ? filtered.length : endIndex,
          );
          
          if (isInitialLoad) {
            _warehouseLocations = pageLocations;
          } else {
            _warehouseLocations.addAll(pageLocations);
          }
          
          _hasMore = endIndex < filtered.length;
        } else {
          _hasMore = false;
        }
        
        _total = filtered.length;
      }

      _applySearchFilter();
      print('[WarehouseLocationListController] After filtering: ${_filteredLocations.length} locations shown');
    } catch (e, stackTrace) {
      print('[WarehouseLocationListController] Error loading warehouse locations: $e');
      print('[WarehouseLocationListController] Error type: ${e.runtimeType}');
      print('[WarehouseLocationListController] Stack trace: $stackTrace');
      
      if (e is ServerFailure) {
        _error = e.message;
      } else {
        _error = '오류 발생: ${e.toString()}';
      }
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 다음 페이지 로드
  Future<void> loadNextPage() async {
    if (!_hasMore || _isLoading) return;
    await loadWarehouseLocations(isInitialLoad: false);
  }

  // 검색
  void search(String query) {
    _searchQuery = query;
    _applySearchFilter();
    notifyListeners();
  }

  // 검색 필터 적용
  void _applySearchFilter() {
    if (_searchQuery.isEmpty) {
      _filteredLocations = List.from(_warehouseLocations);
    } else {
      _filteredLocations = _warehouseLocations.where((location) {
        return location.name.toLowerCase().contains(_searchQuery.toLowerCase()) ||
               location.address.toString().toLowerCase().contains(_searchQuery.toLowerCase());
      }).toList();
    }
  }

  // 필터 설정
  void setFilters({bool? isActive}) {
    _isActive = isActive;
    loadWarehouseLocations();
  }

  // 필터 초기화
  void clearFilters() {
    _isActive = null;
    _searchQuery = '';
    loadWarehouseLocations();
  }

  /// 입고지 추가
  Future<void> addWarehouseLocation(WarehouseLocation location) async {
    try {
      if (useApi && _warehouseService != null) {
        await _warehouseService!.createWarehouseLocation(location);
      } else {
        mockDataService?.addWarehouseLocation(location);
      }
      
      // 목록 새로고침
      await loadWarehouseLocations();
    } catch (e) {
      _error = e.toString();
      notifyListeners();
    }
  }

  /// 입고지 수정
  Future<void> updateWarehouseLocation(WarehouseLocation location) async {
    try {
      if (useApi && _warehouseService != null) {
        await _warehouseService!.updateWarehouseLocation(location);
      } else {
        mockDataService?.updateWarehouseLocation(location);
      }
      
      // 목록에서 업데이트
      final index = _warehouseLocations.indexWhere((l) => l.id == location.id);
      if (index != -1) {
        _warehouseLocations[index] = location;
        _applySearchFilter();
        notifyListeners();
      }
    } catch (e) {
      _error = e.toString();
      notifyListeners();
    }
  }

  /// 입고지 삭제
  Future<void> deleteWarehouseLocation(int id) async {
    try {
      if (useApi && _warehouseService != null) {
        await _warehouseService!.deleteWarehouseLocation(id);
      } else {
        mockDataService?.deleteWarehouseLocation(id);
      }
      
      // 목록에서 제거
      _warehouseLocations.removeWhere((l) => l.id == id);
      _applySearchFilter();
      _total--;
      notifyListeners();
    } catch (e) {
      _error = e.toString();
      notifyListeners();
    }
  }

  // 새로고침
  Future<void> refresh() async {
    await loadWarehouseLocations();
  }

  // 사용 중인 창고 위치 조회
  Future<List<WarehouseLocation>> getInUseWarehouseLocations() async {
    try {
      if (useApi && _warehouseService != null) {
        return await _warehouseService!.getInUseWarehouseLocations();
      } else {
        // Mock 데이터에서는 모든 창고가 사용 중으로 간주
        return mockDataService?.getAllWarehouseLocations() ?? [];
      }
    } catch (e) {
      _error = e.toString();
      notifyListeners();
      return [];
    }
  }
}
