import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport/data/models/model_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';

/// 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,
      children: [
        // Vendor 선택 드롭다운
        _buildVendorDropdown(),
        const SizedBox(height: 16),
        
        // Model 선택 드롭다운 (Vendor 선택 후 활성화)
        _buildModelDropdown(),
      ],
    );
  }

  Widget _buildVendorDropdown() {
    if (_isLoadingVendors) {
      return const Center(child: CircularProgressIndicator());
    }

    final vendors = _vendorController.vendors;
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          widget.isReadOnly ? '제조사 * 🔒' : '제조사 *',
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 8),
        ShadSelect<int>(
          placeholder: const Text('제조사를 선택하세요'),
          options: vendors.map((vendor) {
            return ShadOption(
              value: vendor.id!,
              child: Text(vendor.name),
            );
          }).toList(),
          selectedOptionBuilder: (context, value) {
            final vendor = vendors.firstWhere((v) => v.id == value);
            return Text(vendor.name);
          },
          onChanged: widget.isReadOnly ? null : _onVendorChanged,
          initialValue: _selectedVendorId,
          enabled: !widget.isReadOnly,
        ),
      ],
    );
  }

  Widget _buildModelDropdown() {
    if (_isLoadingModels) {
      return const Center(child: CircularProgressIndicator());
    }

    // Vendor가 선택되지 않으면 비활성화
    final isEnabled = !widget.isReadOnly && _selectedVendorId != null;
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          widget.isReadOnly ? '모델 * 🔒' : '모델 *',
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 8),
        ShadSelect<int>(
          placeholder: Text(
            _selectedVendorId == null 
              ? '먼저 제조사를 선택하세요' 
              : '모델을 선택하세요'
          ),
          options: _filteredModels.map((model) {
            return ShadOption(
              value: model.id,
              child: Text(model.name),
            );
          }).toList(),
          selectedOptionBuilder: (context, value) {
            final model = _filteredModels.firstWhere((m) => m.id == value);
            return Text(model.name);
          },
          onChanged: isEnabled ? _onModelChanged : null,
          initialValue: _selectedModelId,
          enabled: isEnabled,
        ),
      ],
    );
  }
}