import 'package:flutter/material.dart';
import 'base_field.dart';
import '../../../Reuseable/reusable_dropdown_field.dart';

/// Dropdown selection field implementation
class DropdownField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final List<Map<String, dynamic>> options;
  final String valueKey; // id field in option map
  final String displayKey; // display field in option map

  DropdownField({
    required this.fieldKey,
    required this.label,
    required this.hint,
    this.isRequired = false,
    required this.options,
    this.valueKey = 'id',
    this.displayKey = 'name',
  });

  @override
  String? Function(String?)? get validator => (value) {
        if (isRequired && (value == null || value.isEmpty)) {
          return '$label is required';
        }
        return null;
      };

  @override
  Widget buildField({
    required TextEditingController controller,
    required ColorScheme colorScheme,
    VoidCallback? onChanged,
  }) {
    return ReusableDropdownField(
      label: label,
      options: options,
      valueField: valueKey, // id
      uiField: displayKey, // label
      value: controller.text.isNotEmpty ? controller.text : null,
      onChanged: (val) {
        controller.text = val ?? '';
        if (onChanged != null) onChanged();
      },
      onSaved: (val) {
        controller.text = val ?? '';
      },
    );
  }
}
