import 'package:flutter/material.dart';
import 'package:superport/data/models/model/model_dto.dart';
import 'package:superport/data/models/vendor_dto.dart';
import 'package:superport/screens/vendor/controllers/vendor_controller.dart';
import 'package:superport/screens/model/controllers/model_controller.dart';
import 'package:superport/injection_container.dart';
import 'package:superport/screens/common/widgets/standard_dropdown.dart';

/// Equipment 등록/수정 폼에서 사용할 Vendor→Model cascade 선택 위젯
class EquipmentVendorModelSelector extends StatefulWidget {
  final int? initialVendorId;
  final int? initialModelId;
  final Function(int? vendorId, int? modelId) onChanged;
  final bool isReadOnly;

  const EquipmentVendorModelSelector({
    super.key,
    this.initialVendorId,
    this.initialModelId,
    required this.onChanged,
    this.isReadOnly = false,
  });

  @override
  State<EquipmentVendorModelSelector> createState() => _EquipmentVendorModelSelectorState();
}

class _EquipmentVendorModelSelectorState extends State<EquipmentVendorModelSelector> {
  late VendorController _vendorController;
  late ModelController _modelController;
  
  int? _selectedVendorId;
  int? _selectedModelId;
  List<ModelDto> _filteredModels = [];
  bool _isLoadingVendors = false;
  bool _isLoadingModels = false;

  @override
  void initState() {
    super.initState();
    _vendorController = getIt<VendorController>();
    _modelController = getIt<ModelController>();
    
    _selectedVendorId = widget.initialVendorId;
    _selectedModelId = widget.initialModelId;
    
    _loadInitialData();
  }

  Future<void> _loadInitialData() async {
    setState(() => _isLoadingVendors = true);
    
    try {
      // Vendor 목록 로드
      await _vendorController.loadVendors();
      
      // 초기 vendor가 설정되어 있으면 해당 vendor의 모델 로드
      if (_selectedVendorId != null) {
        await _loadModelsForVendor(_selectedVendorId!);
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('데이터 로드 실패: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isLoadingVendors = false);
      }
    }
  }

  Future<void> _loadModelsForVendor(int vendorId) async {
    setState(() {
      _isLoadingModels = true;
      _filteredModels = [];
      _selectedModelId = null; // Vendor 변경 시 Model 선택 초기화
    });
    
    try {
      // 특정 vendor의 모델 목록 로드
      await _modelController.refreshModels();
      
      // vendor에 해당하는 모델만 필터링
      final allModels = _modelController.allModels;
      _filteredModels = allModels.where((model) => model.vendorsId == vendorId).toList();
      
      // 초기 모델이 설정되어 있고 필터링된 목록에 있으면 유지
      if (widget.initialModelId != null && 
          _filteredModels.any((m) => m.id == widget.initialModelId)) {
        _selectedModelId = widget.initialModelId;
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('모델 로드 실패: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isLoadingModels = false);
      }
    }
  }

  void _onVendorChanged(int? vendorId) {
    setState(() {
      _selectedVendorId = vendorId;
      _selectedModelId = null; // Vendor 변경 시 Model 초기화
    });
    
    if (vendorId != null) {
      _loadModelsForVendor(vendorId);
    } else {
      setState(() {
        _filteredModels = [];
      });
    }
    
    // 변경사항 콜백
    widget.onChanged(_selectedVendorId, _selectedModelId);
  }

  void _onModelChanged(int? modelId) {
    setState(() {
      _selectedModelId = modelId;
    });
    
    // 변경사항 콜백
    widget.onChanged(_selectedVendorId, _selectedModelId);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        // Vendor 선택 드롭다운
        _buildVendorDropdown(),
        const SizedBox(height: 16),
        
        // Model 선택 드롭다운 (Vendor 선택 후 활성화)
        _buildModelDropdown(),
      ],
    );
  }

  Widget _buildVendorDropdown() {
    final vendors = _vendorController.vendors;
    
    return Container(
      width: double.infinity,
      child: StandardIntDropdown<VendorDto>(
      label: widget.isReadOnly ? '제조사 * 🔒' : '제조사 *',
      isRequired: true,
      items: vendors,
      isLoading: _isLoadingVendors,
      selectedValue: _selectedVendorId != null 
          ? vendors.where((v) => v.id == _selectedVendorId).firstOrNull
          : null,
      onChanged: (VendorDto? selectedVendor) {
        if (!widget.isReadOnly) {
          _onVendorChanged(selectedVendor?.id);
        }
      },
      itemBuilder: (VendorDto vendor) => Text(vendor.name),
      selectedItemBuilder: (VendorDto vendor) => Text(vendor.name),
      idExtractor: (VendorDto vendor) => vendor.id!,
      placeholder: '제조사를 선택하세요',
      enabled: !widget.isReadOnly,
      ),
    );
  }

  Widget _buildModelDropdown() {
    // Vendor가 선택되지 않으면 비활성화
    final isEnabled = !widget.isReadOnly && _selectedVendorId != null;
    
    return Container(
      width: double.infinity,
      child: StandardIntDropdown<ModelDto>(
      label: widget.isReadOnly ? '모델 * 🔒' : '모델 *',
      isRequired: true,
      items: _filteredModels,
      isLoading: _isLoadingModels,
      selectedValue: _selectedModelId != null 
          ? _filteredModels.where((m) => m.id == _selectedModelId).firstOrNull
          : null,
      onChanged: (ModelDto? selectedModel) {
        if (isEnabled) {
          _onModelChanged(selectedModel?.id);
        }
      },
      itemBuilder: (ModelDto model) => Text(model.name),
      selectedItemBuilder: (ModelDto model) => Text(model.name),
      idExtractor: (ModelDto model) => model.id ?? 0,
      placeholder: _selectedVendorId == null 
          ? '먼저 제조사를 선택하세요' 
          : '모델을 선택하세요',
      enabled: isEnabled,
      ),
    );
  }
}