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

/// Static Multi-Select field
/// - Accepts a static list of display strings
/// - Stores selected values as a comma-separated string in controller
class StaticMultiSelectField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final List<String> options;

  StaticMultiSelectField({
    required this.fieldKey,
    required this.label,
    this.hint = '',
    this.isRequired = false,
    required this.options,
  });

  @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,
  }) {
    final Set<String> selected = controller.text.isEmpty
        ? <String>{}
        : controller.text
            .split(',')
            .map((e) => e.trim())
            .where((e) => e.isNotEmpty)
            .toSet();

    void toggle(String value) {
      if (selected.contains(value)) {
        selected.remove(value);
      } else {
        selected.add(value);
      }
      controller.text = selected.join(',');
      onChanged?.call();
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label,
            style: TextStyle(
                color: colorScheme.onSurface, fontWeight: FontWeight.w600)),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: options.map((opt) {
            final bool isSel = selected.contains(opt);
            return FilterChip(
              label: Text(opt),
              selected: isSel,
              onSelected: (_) => toggle(opt),
            );
          }).toList(),
        ),
        if (validator != null)
          Builder(
            builder: (context) {
              final error = validator!(controller.text);
              return error != null
                  ? Padding(
                      padding: const EdgeInsets.only(top: 6),
                      child: Text(error,
                          style: TextStyle(
                              color: colorScheme.error, fontSize: 12)),
                    )
                  : const SizedBox.shrink();
            },
          )
      ],
    );
  }
}
