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

/// Dynamic multi-select dropdown (no Autocomplete)
/// - Modal list with search and checkboxes
/// - Stores comma-separated selected labels in controller
class DynamicMultiSelectDropdownField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final Future<List<String>> Function() optionsLoader;

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

  @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 _DynamicMultiSelectWidget(
      label: label,
      hint: hint,
      controller: controller,
      colorScheme: colorScheme,
      optionsLoader: optionsLoader,
      validate: validator,
      onChanged: onChanged,
    );
  }
}

class _DynamicMultiSelectWidget extends StatefulWidget {
  final String label;
  final String hint;
  final TextEditingController controller;
  final ColorScheme colorScheme;
  final Future<List<String>> Function() optionsLoader;
  final String? Function(String?)? validate;
  final VoidCallback? onChanged;

  const _DynamicMultiSelectWidget({
    required this.label,
    required this.hint,
    required this.controller,
    required this.colorScheme,
    required this.optionsLoader,
    required this.validate,
    required this.onChanged,
  });

  @override
  State<_DynamicMultiSelectWidget> createState() =>
      _DynamicMultiSelectWidgetState();
}

class _DynamicMultiSelectWidgetState extends State<_DynamicMultiSelectWidget> {
  List<String> _options = const [];
  late final Set<String> _selected;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _selected = widget.controller.text.isEmpty
        ? <String>{}
        : widget.controller.text
            .split(',')
            .map((e) => e.trim())
            .where((e) => e.isNotEmpty)
            .toSet();
    _load();
  }

  Future<void> _load() async {
    try {
      final opts = await widget.optionsLoader();
      setState(() {
        _options = opts;
        _loading = false;
      });
    } catch (_) {
      setState(() => _loading = false);
    }
  }

  Future<void> _openPicker() async {
    final ColorScheme cs = widget.colorScheme;
    String query = '';
    await showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: cs.surface,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) {
        List<String> filtered = _options;
        return StatefulBuilder(
          builder: (context, setSheetState) {
            void applyFilter(String q) {
              query = q;
              setSheetState(() {
                filtered = _options
                    .where((o) => o.toLowerCase().contains(q.toLowerCase()))
                    .toList();
              });
            }

            void toggle(String value) {
              setSheetState(() {
                if (_selected.contains(value)) {
                  _selected.remove(value);
                } else {
                  _selected.add(value);
                }
              });
            }

            return SafeArea(
              child: Padding(
                padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom,
                  left: 16,
                  right: 16,
                  top: 12,
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    TextField(
                      decoration: InputDecoration(
                        hintText: 'Search ${widget.label.toLowerCase()}',
                        prefixIcon: const Icon(Icons.search),
                        border: const OutlineInputBorder(),
                      ),
                      onChanged: applyFilter,
                    ),
                    const SizedBox(height: 12),
                    Flexible(
                      child: filtered.isEmpty
                          ? Center(
                              child: Text('No results',
                                  style: TextStyle(color: cs.onSurfaceVariant)),
                            )
                          : ListView.separated(
                              shrinkWrap: true,
                              itemCount: filtered.length,
                              separatorBuilder: (_, __) => Divider(
                                  height: 1,
                                  color: cs.outline.withOpacity(0.08)),
                              itemBuilder: (context, index) {
                                final name = filtered[index];
                                final isSelected = _selected.contains(name);
                                return CheckboxListTile(
                                  title: Text(name),
                                  value: isSelected,
                                  onChanged: (_) => toggle(name),
                                );
                              },
                            ),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        TextButton(
                          onPressed: () {
                            setState(() {
                              widget.controller.text = '';
                            });
                            _selected.clear();
                            widget.onChanged?.call();
                            Navigator.of(context).pop();
                          },
                          child: const Text('Clear'),
                        ),
                        const Spacer(),
                        ElevatedButton(
                          onPressed: () {
                            setState(() {
                              widget.controller.text = _selected.join(',');
                            });
                            widget.onChanged?.call();
                            Navigator.of(context).pop();
                          },
                          child: const Text('Done'),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return const LinearProgressIndicator(minHeight: 2);
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ModernTextField(
          label: widget.label,
          hint: widget.hint,
          readOnly: true,
          controller: TextEditingController(text: _selected.join(', ')),
          validator: widget.validate,
          onTap: _openPicker,
          suffixIcon: const Icon(Icons.arrow_drop_down),
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          children: _selected
              .map((v) => Chip(
                    label: Text(v),
                    onDeleted: () {
                      setState(() {
                        _selected.remove(v);
                        widget.controller.text = _selected.join(',');
                      });
                      widget.onChanged?.call();
                    },
                  ))
              .toList(),
        ),
      ],
    );
  }
}
