import 'package:flutter/material.dart';
import 'package:injectable/injectable.dart';
import 'package:superport/data/models/model_dto.dart';
import 'package:superport/data/models/vendor_dto.dart';
import 'package:superport/domain/usecases/model_usecase.dart';
import 'package:superport/domain/usecases/vendor_usecase.dart';

/// Model 관리 화면의 상태 관리 Controller
@lazySingleton
class ModelController extends ChangeNotifier {
  final ModelUseCase _modelUseCase;
  final VendorUseCase _vendorUseCase;

  ModelController(this._modelUseCase, this._vendorUseCase);

  // 상태 변수들
  List<ModelDto> _models = [];
  List<ModelDto> _filteredModels = [];
  List<VendorDto> _vendors = [];
  final Map<int, List<ModelDto>> _modelsByVendor = {};
  
  bool _isLoading = false;
  bool _isSubmitting = false;
  String? _errorMessage;
  String _searchQuery = '';
  int? _selectedVendorId;
  
  // Getters
  List<ModelDto> get models => _filteredModels;
  List<ModelDto> get allModels => _models;
  List<VendorDto> get vendors => _vendors;
  Map<int, List<ModelDto>> get modelsByVendor => _modelsByVendor;
  bool get isLoading => _isLoading;
  bool get isSubmitting => _isSubmitting;
  String? get errorMessage => _errorMessage;
  String get searchQuery => _searchQuery;
  int? get selectedVendorId => _selectedVendorId;

  /// 초기 데이터 로드
  Future<void> loadInitialData() async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      // Vendor와 Model 데이터 병렬 로드
      final results = await Future.wait([
        _vendorUseCase.getVendors(),
        _modelUseCase.getModels(),
      ]);

      _vendors = List<VendorDto>.from(results[0] as List<VendorDto>);
      _models = List<ModelDto>.from(results[1] as List<ModelDto>);
      _filteredModels = List.from(_models);
      
      // Vendor별로 모델 그룹핑
      await _groupModelsByVendor();
      
    } catch (e) {
      _errorMessage = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 모델 목록 새로고침
  Future<void> refreshModels() async {
    _errorMessage = null;
    
    try {
      _models = List.from(await _modelUseCase.getModels(vendorId: _selectedVendorId));
      _applyFilters();
      await _groupModelsByVendor();
    } catch (e) {
      _errorMessage = e.toString();
    } finally {
      notifyListeners();
    }
  }

  /// 모델 생성
  Future<bool> createModel({
    required int vendorsId,
    required String name,
  }) async {
    _isSubmitting = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final newModel = await _modelUseCase.createModel(
        vendorsId: vendorsId,
        name: name,
      );

      // 목록에 추가
      _models = [..._models, newModel];
      _applyFilters();
      await _groupModelsByVendor();
      
      return true;
    } catch (e) {
      _errorMessage = e.toString();
      return false;
    } finally {
      _isSubmitting = false;
      notifyListeners();
    }
  }

  /// 모델 수정
  Future<bool> updateModel({
    required int id,
    required int vendorsId,
    required String name,
  }) async {
    _isSubmitting = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final updatedModel = await _modelUseCase.updateModel(
        id: id,
        vendorsId: vendorsId,
        name: name,
      );

      // 목록에서 업데이트
      final index = _models.indexWhere((m) => m.id == id);
      if (index != -1) {
        _models = _models.map((model) => 
          model.id == id ? updatedModel : model
        ).toList();
        _applyFilters();
        await _groupModelsByVendor();
      }
      
      return true;
    } catch (e) {
      _errorMessage = e.toString();
      return false;
    } finally {
      _isSubmitting = false;
      notifyListeners();
    }
  }

  /// 모델 삭제 (Soft Delete)
  Future<bool> deleteModel(int id) async {
    _isSubmitting = true;
    _errorMessage = null;
    notifyListeners();

    try {
      await _modelUseCase.deleteModel(id);
      
      // 목록에서 제거 또는 비활성화 표시
      _models = _models.where((m) => m.id != id).toList();
      _applyFilters();
      await _groupModelsByVendor();
      
      return true;
    } catch (e) {
      _errorMessage = e.toString();
      return false;
    } finally {
      _isSubmitting = false;
      notifyListeners();
    }
  }

  /// 검색어 설정
  void setSearchQuery(String query) {
    _searchQuery = query;
    _applyFilters();
    notifyListeners();
  }

  /// Vendor 필터 설정
  void setVendorFilter(int? vendorId) {
    _selectedVendorId = vendorId;
    _applyFilters();
    notifyListeners();
  }

  /// 필터 적용
  void _applyFilters() {
    _filteredModels = _models.where((model) {
      // Vendor 필터
      if (_selectedVendorId != null && model.vendorsId != _selectedVendorId) {
        return false;
      }
      
      // 검색어 필터
      if (_searchQuery.isNotEmpty) {
        final query = _searchQuery.toLowerCase();
        return model.name.toLowerCase().contains(query);
      }
      
      return true;
    }).toList();
  }

  /// Vendor별 모델 그룹핑
  Future<void> _groupModelsByVendor() async {
    _modelsByVendor.clear();
    
    for (final model in _models) {
      _modelsByVendor.putIfAbsent(model.vendorsId, () => []).add(model);
    }
  }

  /// Vendor ID로 Vendor 정보 가져오기
  VendorDto? getVendorById(int vendorId) {
    try {
      return _vendors.firstWhere((v) => v.id == vendorId);
    } catch (_) {
      return null;
    }
  }

  /// 특정 Vendor의 모델 목록 가져오기
  List<ModelDto> getModelsByVendor(int vendorId) {
    return _modelsByVendor[vendorId] ?? [];
  }

  /// 에러 메시지 클리어
  void clearError() {
    _errorMessage = null;
    notifyListeners();
  }

  /// 컨트롤러 리셋
  void reset() {
    _models.clear();
    _filteredModels.clear();
    _vendors.clear();
    _modelsByVendor.clear();
    _isLoading = false;
    _isSubmitting = false;
    _errorMessage = null;
    _searchQuery = '';
    _selectedVendorId = null;
    notifyListeners();
  }

  @override
  void dispose() {
    reset();
    super.dispose();
  }
}