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

/// Dynamic single-select dropdown (no Autocomplete)
/// - Opens a modal list with search
/// - Stores selected id in controller, displays label
class DynamicDropdownField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final Future<List<Map<String, dynamic>>> Function() optionsLoader;
  final String valueKey;
  final String displayKey;

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

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

class _DynamicDropdownWidget extends StatefulWidget {
  final String label;
  final String hint;
  final TextEditingController controller;
  final ColorScheme colorScheme;
  final Future<List<Map<String, dynamic>>> Function() optionsLoader;
  final String valueKey;
  final String displayKey;
  final String? Function(String?)? validate;
  final VoidCallback? onChanged;

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

  @override
  State<_DynamicDropdownWidget> createState() => _DynamicDropdownWidgetState();
}

class _DynamicDropdownWidgetState extends State<_DynamicDropdownWidget> {
  List<Map<String, dynamic>> _options = const [];
  String _uiLabel = '';
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    try {
      final opts = await widget.optionsLoader();
      setState(() {
        _options = opts;
        _loading = false;
      });
      if (widget.controller.text.isNotEmpty) {
        final match = _options.firstWhere(
          (o) =>
              (o[widget.valueKey]?.toString() ?? '') == widget.controller.text,
          orElse: () => const {},
        );
        setState(() {
          _uiLabel = match.isNotEmpty
              ? (match[widget.displayKey]?.toString() ?? '')
              : '';
        });
      }
    } 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<Map<String, dynamic>> filtered = _options;
        return StatefulBuilder(
          builder: (context, setSheetState) {
            void applyFilter(String q) {
              query = q;
              setSheetState(() {
                filtered = _options
                    .where((o) => (o[widget.displayKey]?.toString() ?? '')
                        .toLowerCase()
                        .contains(q.toLowerCase()))
                    .toList();
              });
            }

            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 o = filtered[index];
                                final id = o[widget.valueKey]?.toString() ?? '';
                                final name =
                                    o[widget.displayKey]?.toString() ?? '';
                                final isSelected = widget.controller.text == id;
                                return ListTile(
                                  title: Text(name),
                                  trailing: isSelected
                                      ? Icon(Icons.check, color: cs.primary)
                                      : null,
                                  onTap: () {
                                    setState(() {
                                      widget.controller.text = id;
                                      _uiLabel = name;
                                    });
                                    widget.onChanged?.call();
                                    Navigator.of(context).pop();
                                  },
                                );
                              },
                            ),
                    ),
                    const SizedBox(height: 8),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return const LinearProgressIndicator(minHeight: 2);
    }
    return ModernTextField(
      label: widget.label,
      hint: widget.hint,
      readOnly: true,
      controller: TextEditingController(text: _uiLabel),
      validator: (v) => widget.validate?.call(widget.controller.text),
      onTap: _openPicker,
      suffixIcon: const Icon(Icons.arrow_drop_down),
    );
  }
}
