import 'package:dio/dio.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get_it/get_it.dart';
import 'package:shared_preferences/shared_preferences.dart';

// Core
import 'core/storage/secure_storage.dart';

// Data Sources
import 'data/datasources/remote/api_client.dart';
import 'data/datasources/remote/administrator_remote_datasource.dart';
import 'data/datasources/remote/auth_remote_datasource.dart';
import 'data/datasources/remote/company_remote_datasource.dart';
import 'data/datasources/remote/equipment_remote_datasource.dart';
import 'data/datasources/remote/lookup_remote_datasource.dart';
import 'data/datasources/remote/maintenance_remote_datasource.dart';
import 'data/datasources/remote/dashboard_remote_datasource.dart';
import 'data/datasources/remote/user_remote_datasource.dart';
import 'data/datasources/remote/warehouse_location_remote_datasource.dart';
import 'data/datasources/remote/warehouse_remote_datasource.dart';
// import 'data/datasources/interceptors/api_interceptor.dart'; // Legacy interceptor (no longer used)

// Repositories
import 'domain/repositories/administrator_repository.dart';
import 'domain/repositories/auth_repository.dart';
import 'domain/repositories/company_repository.dart';
import 'domain/repositories/equipment_repository.dart';
import 'domain/repositories/user_repository.dart';
import 'domain/repositories/warehouse_location_repository.dart';
import 'data/repositories/administrator_repository_impl.dart';
import 'data/repositories/auth_repository_impl.dart';
import 'data/repositories/company_repository_impl.dart';
import 'data/repositories/equipment_repository_impl.dart';
import 'data/repositories/user_repository_impl.dart';
import 'data/repositories/warehouse_location_repository_impl.dart';
import 'data/repositories/vendor_repository.dart';
import 'domain/usecases/vendor_usecase.dart';
import 'screens/vendor/controllers/vendor_controller.dart';
// Models - Repository & DataSource
import 'domain/repositories/model_repository.dart';
import 'data/repositories/model_repository_impl.dart';
import 'data/datasources/remote/model_remote_datasource.dart';

// Models - Individual UseCases
import 'domain/usecases/models/get_models_usecase.dart';
import 'domain/usecases/models/get_model_detail_usecase.dart';
import 'domain/usecases/models/create_model_usecase.dart';
import 'domain/usecases/models/update_model_usecase.dart';
import 'domain/usecases/models/delete_model_usecase.dart';
import 'domain/usecases/models/restore_model_usecase.dart';
import 'domain/usecases/models/get_models_by_vendor_usecase.dart';

// Models - Controller
import 'screens/model/controllers/model_controller.dart';
import 'screens/equipment/controllers/equipment_form_controller.dart';
import 'screens/equipment/controllers/equipment_list_controller.dart';
import 'screens/equipment/controllers/equipment_controller.dart';
import 'screens/company/controllers/company_controller.dart';
import 'data/repositories/equipment_history_repository.dart';
import 'domain/usecases/equipment_history_usecase.dart';
import 'screens/equipment/controllers/equipment_history_controller.dart';
import 'data/repositories/maintenance_repository.dart';
import 'data/repositories/maintenance_repository_impl.dart';
import 'domain/usecases/maintenance_usecase.dart';
import 'screens/maintenance/controllers/maintenance_controller.dart';
// Maintenance Stats (새로운 대시보드 기능)
import 'data/repositories/maintenance_stats_repository.dart';
import 'data/repositories/maintenance_stats_repository_impl.dart';
import 'domain/usecases/get_maintenance_stats_usecase.dart';
import 'screens/maintenance/controllers/maintenance_dashboard_controller.dart';
import 'data/repositories/zipcode_repository.dart';
import 'domain/usecases/zipcode_usecase.dart';
import 'screens/zipcode/controllers/zipcode_controller.dart';
import 'data/repositories/rent_repository_impl.dart';
import 'domain/repositories/rent_repository.dart';
import 'domain/usecases/rent_usecase.dart';
import 'screens/rent/controllers/rent_controller.dart';
import 'services/inventory_history_service.dart';
import 'screens/inventory/controllers/inventory_history_controller.dart';

// Use Cases - Auth
import 'domain/usecases/auth/login_usecase.dart';
import 'domain/usecases/auth/logout_usecase.dart';
import 'domain/usecases/auth/get_current_user_usecase.dart';
import 'domain/usecases/auth/check_auth_status_usecase.dart';
import 'domain/usecases/auth/refresh_token_usecase.dart';

// Use Cases - Company
import 'domain/usecases/company/get_companies_usecase.dart';
import 'domain/usecases/company/get_company_detail_usecase.dart';
import 'domain/usecases/company/create_company_usecase.dart';
import 'domain/usecases/company/update_company_usecase.dart';
import 'domain/usecases/company/delete_company_usecase.dart';
import 'domain/usecases/company/toggle_company_status_usecase.dart';
import 'domain/usecases/company/get_company_hierarchy_usecase.dart';
import 'domain/usecases/company/update_parent_company_usecase.dart';
import 'domain/usecases/company/validate_company_deletion_usecase.dart';
import 'domain/usecases/company/restore_company_usecase.dart';

// Use Cases - User
import 'domain/usecases/user/get_users_usecase.dart';
import 'domain/usecases/user/create_user_usecase.dart';
import 'domain/usecases/user/check_username_availability_usecase.dart';

// Use Cases - Equipment
import 'domain/usecases/equipment/get_equipments_usecase.dart';
import 'domain/usecases/equipment/get_equipment_detail_usecase.dart';
import 'domain/usecases/equipment/create_equipment_usecase.dart';
import 'domain/usecases/equipment/update_equipment_usecase.dart';
import 'domain/usecases/equipment/delete_equipment_usecase.dart';
import 'domain/usecases/equipment/search_equipment_usecase.dart';
import 'domain/usecases/equipment/restore_equipment_usecase.dart';
import 'domain/usecases/equipment/equipment_in_usecase.dart';
import 'domain/usecases/equipment/equipment_out_usecase.dart';
import 'domain/usecases/equipment/get_equipment_history_usecase.dart';


// Use Cases - Warehouse Location
import 'domain/usecases/warehouse_location/get_warehouse_locations_usecase.dart';
import 'domain/usecases/warehouse_location/get_warehouse_location_detail_usecase.dart';
import 'domain/usecases/warehouse_location/create_warehouse_location_usecase.dart';
import 'domain/usecases/warehouse_location/update_warehouse_location_usecase.dart';
import 'domain/usecases/warehouse_location/delete_warehouse_location_usecase.dart';

// Services (기존 서비스들과의 호환성을 위해 유지)
import 'services/auth_service.dart';
import 'services/company_service.dart';
import 'services/equipment_service.dart';
import 'core/services/lookups_service.dart';
import 'services/administrator_service.dart';
import 'services/user_service.dart';
import 'services/warehouse_service.dart';
import 'services/dashboard_service.dart';

// Administrator
import 'domain/usecases/administrator_usecase.dart';
import 'screens/administrator/controllers/administrator_controller.dart';

final sl = GetIt.instance;
final getIt = sl; // Alias for compatibility

  Future<void> init() async {
  // External
  final sharedPreferences = await SharedPreferences.getInstance();
  sl.registerLazySingleton(() => sharedPreferences);
  
  // Core
  sl.registerLazySingleton(() => SecureStorage());
  sl.registerLazySingleton(() => const FlutterSecureStorage());
  
  // API Client (centralized Dio + interceptors)
  sl.registerLazySingleton(() => ApiClient());
  
  // Dio — use ApiClient's configured Dio to avoid divergence
  sl.registerLazySingleton<Dio>(() => sl<ApiClient>().dio);
  
  // Data Sources
  sl.registerLazySingleton<AdministratorRemoteDataSource>(
    () => AdministratorRemoteDataSourceImpl(sl<ApiClient>()),
  );
  sl.registerLazySingleton<AuthRemoteDataSource>(
    () => AuthRemoteDataSourceImpl(sl<ApiClient>()),
  );
  sl.registerLazySingleton<CompanyRemoteDataSource>(
    () => CompanyRemoteDataSourceImpl(sl<ApiClient>()),
  );
  sl.registerLazySingleton<EquipmentRemoteDataSource>(
    () => EquipmentRemoteDataSourceImpl(),
  );
  sl.registerLazySingleton<LookupRemoteDataSource>(
    () => LookupRemoteDataSourceImpl(sl<ApiClient>()),
  );
  sl.registerLazySingleton<ModelRemoteDataSource>(
    () => ModelRemoteDataSourceImpl(),
  );
  sl.registerLazySingleton<MaintenanceRemoteDataSource>(
    () => MaintenanceRemoteDataSourceImpl(),
  );
  sl.registerLazySingleton<DashboardRemoteDataSource>(
    () => DashboardRemoteDataSourceImpl(sl<ApiClient>()),
  );
  sl.registerLazySingleton<UserRemoteDataSource>(
    () => UserRemoteDataSourceImpl(sl<ApiClient>()),
  );
  sl.registerLazySingleton<WarehouseLocationRemoteDataSource>(
    () => WarehouseLocationRemoteDataSourceImpl(apiClient: sl<ApiClient>()),
  );
  sl.registerLazySingleton<WarehouseRemoteDataSource>(
    () => WarehouseRemoteDataSourceImpl(apiClient: sl<ApiClient>()),
  );
  
  // Repositories
  sl.registerLazySingleton<AdministratorRepository>(
    () => AdministratorRepositoryImpl(sl<AdministratorRemoteDataSource>()),
  );
  sl.registerLazySingleton<AuthRepository>(
    () => AuthRepositoryImpl(
      remoteDataSource: sl<AuthRemoteDataSource>(),
      sharedPreferences: sl<SharedPreferences>(),
      secureStorage: sl<FlutterSecureStorage>(),
    ),
  );
  sl.registerLazySingleton<CompanyRepository>(
    () => CompanyRepositoryImpl(remoteDataSource: sl<CompanyRemoteDataSource>()),
  );
  sl.registerLazySingleton<EquipmentRepository>(
    () => EquipmentRepositoryImpl(remoteDataSource: sl<EquipmentRemoteDataSource>()),
  );
  sl.registerLazySingleton<UserRepository>(
    () => UserRepositoryImpl(sl<UserRemoteDataSource>()),
  );
  sl.registerLazySingleton<WarehouseLocationRepository>(
    () => WarehouseLocationRepositoryImpl(remoteDataSource: sl<WarehouseLocationRemoteDataSource>()),
  );
  sl.registerLazySingleton<VendorRepository>(
    () => VendorRepositoryImpl(sl<ApiClient>()),
  );
  sl.registerLazySingleton<ModelRepository>(
    () => ModelRepositoryImpl(remoteDataSource: sl<ModelRemoteDataSource>()),
  );
  sl.registerLazySingleton<EquipmentHistoryRepository>(
    () => EquipmentHistoryRepositoryImpl(sl<Dio>()),
  );
  sl.registerLazySingleton<MaintenanceRepository>(
    () => MaintenanceRepositoryImpl(
      remoteDataSource: sl<MaintenanceRemoteDataSource>(),
    ),
  );
  // Maintenance Stats Repository (대시보드 통계용)
  sl.registerLazySingleton<MaintenanceStatsRepository>(
    () => MaintenanceStatsRepositoryImpl(
      remoteDataSource: sl<MaintenanceRemoteDataSource>(),
    ),
  );
  sl.registerLazySingleton<ZipcodeRepository>(
    () => ZipcodeRepositoryImpl(sl<ApiClient>()),
  );
  sl.registerLazySingleton<RentRepository>(
    () => RentRepositoryImpl(dio: sl<Dio>()),
  );
  
  // Use Cases - Auth
  sl.registerLazySingleton(() => LoginUseCase(sl<AuthRepository>()));  // Repository 사용
  sl.registerLazySingleton(() => LogoutUseCase(sl<AuthRepository>()));
  sl.registerLazySingleton(() => GetCurrentUserUseCase(sl<AuthRepository>()));
  sl.registerLazySingleton(() => CheckAuthStatusUseCase(sl<AuthRepository>()));  // Repository 사용
  sl.registerLazySingleton(() => RefreshTokenUseCase(sl<AuthRepository>()));
  
  // Use Cases - Company
  sl.registerLazySingleton(() => GetCompaniesUseCase(sl<CompanyRepository>()));
  sl.registerLazySingleton(() => GetCompanyDetailUseCase(sl<CompanyRepository>()));
  sl.registerLazySingleton(() => CreateCompanyUseCase(sl<CompanyRepository>()));
  sl.registerLazySingleton(() => UpdateCompanyUseCase(sl<CompanyRepository>()));
  sl.registerLazySingleton(() => DeleteCompanyUseCase(sl<CompanyRepository>()));
  sl.registerLazySingleton(() => ToggleCompanyStatusUseCase(sl<CompanyRepository>()));
  sl.registerLazySingleton(() => GetCompanyHierarchyUseCase(sl<CompanyRepository>()));
  sl.registerLazySingleton(() => UpdateParentCompanyUseCase(sl<CompanyRepository>()));
  sl.registerLazySingleton(() => ValidateCompanyDeletionUseCase(sl<CompanyRepository>()));
  sl.registerLazySingleton(() => RestoreCompanyUseCase(sl<CompanyRepository>()));
  
  // Use Cases - User (Repository 사용으로 마이그레이션 완료)
  sl.registerLazySingleton(() => GetUsersUseCase(sl<UserRepository>()));
  sl.registerLazySingleton(() => CreateUserUseCase(sl<UserRepository>()));
  sl.registerLazySingleton(() => CheckUsernameAvailabilityUseCase());
  
  // Use Cases - Equipment
  sl.registerLazySingleton(() => GetEquipmentsUseCase(sl<EquipmentRepository>()));
  sl.registerLazySingleton(() => GetEquipmentDetailUseCase(sl<EquipmentRepository>()));
  sl.registerLazySingleton(() => CreateEquipmentUseCase(sl<EquipmentRepository>()));
  sl.registerLazySingleton(() => UpdateEquipmentUseCase(sl<EquipmentRepository>()));
  sl.registerLazySingleton(() => DeleteEquipmentUseCase(sl<EquipmentRepository>()));
  sl.registerLazySingleton(() => GetEquipmentBySerialUseCase(sl<EquipmentRepository>()));
  sl.registerLazySingleton(() => GetEquipmentByBarcodeUseCase(sl<EquipmentRepository>()));
  sl.registerLazySingleton(() => GetEquipmentsByCompanyUseCase(sl<EquipmentRepository>()));
  sl.registerLazySingleton(() => RestoreEquipmentUseCase(sl<EquipmentRepository>()));
  sl.registerLazySingleton(() => EquipmentInUseCase(sl<EquipmentHistoryUseCase>()));  // EquipmentHistoryUseCase 사용 (백엔드 스키마 기반)
  sl.registerLazySingleton(() => EquipmentOutUseCase(sl<EquipmentHistoryUseCase>()));  // EquipmentHistoryUseCase 사용 (백엔드 스키마 기반)
  sl.registerLazySingleton(() => GetEquipmentHistoryUseCase(sl<EquipmentHistoryUseCase>()));  // EquipmentHistoryUseCase 사용 (백엔드 스키마 기반)
  
  
  // Use Cases - Warehouse Location
  sl.registerLazySingleton(() => GetWarehouseLocationsUseCase(sl<WarehouseLocationRepository>()));  // Repository 사용 (이미 구현됨)
  sl.registerLazySingleton(() => GetWarehouseLocationDetailUseCase(sl<WarehouseLocationRepository>()));  // Repository 사용 (이미 구현됨)
  sl.registerLazySingleton(() => CreateWarehouseLocationUseCase(sl<WarehouseLocationRepository>()));  // Repository 사용 (이미 구현됨)
  sl.registerLazySingleton(() => UpdateWarehouseLocationUseCase(sl<WarehouseLocationRepository>()));  // Repository 사용 (이미 구현됨)
  sl.registerLazySingleton(() => DeleteWarehouseLocationUseCase(sl<WarehouseLocationRepository>()));  // Repository 사용 (이미 구현됨)
  
  // Use Cases - Vendor
  sl.registerLazySingleton<VendorUseCase>(
    () => VendorUseCaseImpl(sl<VendorRepository>()),
  );
  
  // Use Cases - Models (Individual UseCases)
  sl.registerLazySingleton(() => GetModelsUseCase(sl<ModelRepository>()));
  sl.registerLazySingleton(() => GetModelDetailUseCase(sl<ModelRepository>()));
  sl.registerLazySingleton(() => CreateModelUseCase(sl<ModelRepository>()));
  sl.registerLazySingleton(() => UpdateModelUseCase(sl<ModelRepository>()));
  sl.registerLazySingleton(() => DeleteModelUseCase(sl<ModelRepository>()));
  sl.registerLazySingleton(() => RestoreModelUseCase(sl<ModelRepository>()));
  sl.registerLazySingleton(() => GetModelsByVendorUseCase(sl<ModelRepository>()));
  
  // Use Cases - Equipment History
  sl.registerLazySingleton<EquipmentHistoryUseCase>(
    () => EquipmentHistoryUseCase(sl<EquipmentHistoryRepository>()),
  );
  
  // Use Cases - Maintenance
  sl.registerLazySingleton<MaintenanceUseCase>(
    () => MaintenanceUseCase(repository: sl<MaintenanceRepository>()),
  );
  
  // Use Cases - Maintenance Stats (대시보드용)
  sl.registerLazySingleton<GetMaintenanceStatsUseCase>(
    () => GetMaintenanceStatsUseCase(repository: sl<MaintenanceStatsRepository>()),
  );
  
  // Use Cases - Zipcode
  sl.registerLazySingleton<ZipcodeUseCase>(
    () => ZipcodeUseCaseImpl(sl<ZipcodeRepository>()),
  );
  
  // Use Cases - Rent
  sl.registerLazySingleton<RentUseCase>(
    () => RentUseCase(sl<RentRepository>()),
  );
  
  // Use Cases - Administrator
  sl.registerLazySingleton<AdministratorUseCase>(
    () => AdministratorUseCaseImpl(sl<AdministratorRepository>()),
  );
  
  // Controllers
  sl.registerFactory(() => VendorController(sl<VendorUseCase>()));
  sl.registerFactory(() => ModelController(
    sl<GetModelsUseCase>(),
    sl<CreateModelUseCase>(),
    sl<UpdateModelUseCase>(),
    sl<DeleteModelUseCase>(),
    sl<VendorUseCase>(),
  ));
  sl.registerFactory(() => EquipmentListController());
  sl.registerFactory(() => EquipmentFormController(
    sl<CreateEquipmentUseCase>(),
    sl<UpdateEquipmentUseCase>(),
    sl<GetEquipmentDetailUseCase>(),
    sl<GetCompaniesUseCase>(),
    sl<GetModelsUseCase>(),
    sl<VendorUseCase>(),
  ));
  sl.registerFactory(() => EquipmentHistoryController(useCase: sl<EquipmentHistoryUseCase>()));
  sl.registerFactory(() => MaintenanceController(
    maintenanceUseCase: sl<MaintenanceUseCase>(),
    equipmentHistoryRepository: sl<EquipmentHistoryRepository>(),
  ));
  // Maintenance Dashboard Controller (대시보드용)
  sl.registerFactory(() => MaintenanceDashboardController(getMaintenanceStatsUseCase: sl<GetMaintenanceStatsUseCase>()));
  sl.registerFactory(() => ZipcodeController(sl<ZipcodeUseCase>()));
  sl.registerFactory(() => RentController(sl<RentUseCase>()));
  sl.registerFactory(() => AdministratorController(sl<AdministratorUseCase>()));
  sl.registerFactory(() => EquipmentController(
    sl<GetEquipmentsUseCase>(),
    sl<GetEquipmentDetailUseCase>(),
    sl<CreateEquipmentUseCase>(),
    sl<UpdateEquipmentUseCase>(),
    sl<DeleteEquipmentUseCase>(),
    sl<RestoreEquipmentUseCase>(),
  ));
  sl.registerFactory(() => CompanyController(
    sl<GetCompaniesUseCase>(),
    sl<GetCompanyDetailUseCase>(),
    sl<CreateCompanyUseCase>(),
    sl<UpdateCompanyUseCase>(),
    sl<DeleteCompanyUseCase>(),
    sl<RestoreCompanyUseCase>(),
  ));
  
  // Services (기존 서비스들과의 호환성을 위해 유지)
  sl.registerLazySingleton<AuthService>(
    () => AuthServiceImpl(
      sl<AuthRemoteDataSource>(),
      sl<FlutterSecureStorage>(),
    ),
  );
  sl.registerLazySingleton<CompanyService>(
    () => CompanyService(sl<CompanyRemoteDataSource>()),
  );
  sl.registerLazySingleton<EquipmentService>(
    () => EquipmentService(),
  );
  // LookupsService (Phase 4A에서 추가된 새로운 서비스)
  sl.registerLazySingleton<LookupsService>(
    () => LookupsService(sl<LookupRemoteDataSource>()),
  );
  sl.registerLazySingleton<UserService>(
    () => UserService(sl<UserRemoteDataSource>()),
  );
  sl.registerLazySingleton<AdministratorService>(
    () => AdministratorService(sl<AdministratorRemoteDataSource>()),
  );
  sl.registerLazySingleton<WarehouseService>(
    () => WarehouseService(),
  );
  sl.registerLazySingleton<DashboardService>(
    () => DashboardServiceImpl(sl<DashboardRemoteDataSource>()),
  );
  
  // 재고 이력 관리 서비스 (새로 추가)
  sl.registerLazySingleton<InventoryHistoryService>(
    () => InventoryHistoryService(
      historyRepository: sl<EquipmentHistoryRepository>(),
      equipmentDetailUseCase: sl<GetEquipmentDetailUseCase>(),
    ),
  );
  
  // 재고 이력 컨트롤러 (새로 추가)
  sl.registerFactory(() => InventoryHistoryController(
    service: sl<InventoryHistoryService>(),
  ));
}
