import 'package:flutter/material.dart';
import 'base_field.dart';
import '../../../shared/widgets/inputs/modern_text_field.dart';

class AutocompleteMultiSelectField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final Future<List<String>> Function() optionsLoader;

  AutocompleteMultiSelectField({
    required this.fieldKey,
    required this.label,
    required this.hint,
    required this.optionsLoader,
    this.isRequired = false,
  });

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

  @override
  Map<String, dynamic>? get customProperties => const {
        'isMultiSelect': true,
      };

  @override
  Widget buildField({
    required TextEditingController controller,
    required ColorScheme colorScheme,
    VoidCallback? onChanged,
  }) {
    return FutureBuilder<List<String>>(
      future: optionsLoader(),
      builder: (context, snapshot) {
        final options = snapshot.data ?? const <String>[];
        final Set<String> selected = controller.text.isEmpty
            ? <String>{}
            : controller.text
                .split(',')
                .map((e) => e.trim())
                .where((e) => e.isNotEmpty)
                .toSet();

        void toggleSelection(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: [
            Autocomplete<String>(
              optionsBuilder: (TextEditingValue tev) {
                if (tev.text.isEmpty) return const Iterable<String>.empty();
                return options.where((opt) =>
                    opt.toLowerCase().contains(tev.text.toLowerCase()));
              },
              onSelected: (String selection) => toggleSelection(selection),
              fieldViewBuilder:
                  (context, textController, focusNode, onFieldSubmitted) {
                return ModernTextField(
                  label: label,
                  hint: hint,
                  controller: textController,
                  focusNode: focusNode,
                  onSubmitted: (_) {
                    final v = textController.text.trim();
                    if (v.isNotEmpty) {
                      toggleSelection(v);
                      textController.clear();
                    }
                  },
                  suffixIcon: textController.text.isNotEmpty
                      ? IconButton(
                          icon: const Icon(Icons.clear),
                          onPressed: () {
                            textController.clear();
                            onChanged?.call();
                          },
                        )
                      : const Icon(Icons.search),
                  onChanged: (_) => onChanged?.call(),
                );
              },
              optionsViewBuilder: (context, onSelected, optionsIt) {
                final list = optionsIt.toList();
                return Align(
                  alignment: Alignment.topLeft,
                  child: Material(
                    elevation: 6,
                    color: colorScheme.surface,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                      side: BorderSide(
                          color: colorScheme.outline.withOpacity(0.15)),
                    ),
                    child: ConstrainedBox(
                      constraints:
                          const BoxConstraints(maxHeight: 280, minWidth: 240),
                      child: list.isEmpty
                          ? Padding(
                              padding: const EdgeInsets.all(16),
                              child: Row(
                                children: [
                                  Icon(Icons.info_outline,
                                      color: colorScheme.onSurfaceVariant),
                                  const SizedBox(width: 8),
                                  Expanded(
                                    child: Text(
                                      'No results',
                                      style: TextStyle(
                                          color: colorScheme.onSurfaceVariant),
                                    ),
                                  ),
                                ],
                              ),
                            )
                          : ListView.separated(
                              shrinkWrap: true,
                              padding: const EdgeInsets.symmetric(vertical: 8),
                              itemCount: list.length,
                              separatorBuilder: (_, __) => Divider(
                                  height: 1,
                                  color: colorScheme.outline.withOpacity(0.08)),
                              itemBuilder: (context, index) {
                                final opt = list[index];
                                return ListTile(
                                  title: Text(opt),
                                  onTap: () {
                                    onSelected(opt);
                                  },
                                );
                              },
                            ),
                    ),
                  ),
                );
              },
            ),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              children: selected
                  .map((value) => Chip(
                        label: Text(value),
                        onDeleted: () => toggleSelection(value),
                      ))
                  .toList(),
            ),
            if (snapshot.connectionState == ConnectionState.waiting)
              const Padding(
                padding: EdgeInsets.only(top: 8.0),
                child: LinearProgressIndicator(minHeight: 2),
              ),
            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();
                },
              )
          ],
        );
      },
    );
  }
}
