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

/// Value List Picker
/// - Shows an icon button
/// - Loads list from API and displays as modal cards
/// - On selecting an item, fills multiple form fields based on mapping
class ValueListPickerField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final Future<List<Map<String, dynamic>>> Function() optionsLoader;
  final Map<String, String> fillMappings; // sourceKey -> targetFieldKey in form
  final IconData icon;

  ValueListPickerField({
    required this.fieldKey,
    required this.label,
    this.hint = '',
    this.isRequired = false,
    required this.optionsLoader,
    required this.fillMappings,
    this.icon = Icons.playlist_add_check,
  });

  @override
  String? Function(String?)? get validator => null;

  @override
  Map<String, dynamic>? get customProperties => const {
        'excludeFromSubmit': true, // helper-only, no direct submission
      };

  @override
  Widget buildField({
    required TextEditingController controller,
    required ColorScheme colorScheme,
    VoidCallback? onChanged,
  }) {
    return _ValueListPickerWidget(
      label: label,
      colorScheme: colorScheme,
      optionsLoader: optionsLoader,
      fillMappings: fillMappings,
      icon: icon,
    );
  }
}

class _ValueListPickerWidget extends StatefulWidget {
  final String label;
  final ColorScheme colorScheme;
  final Future<List<Map<String, dynamic>>> Function() optionsLoader;
  final Map<String, String> fillMappings;
  final IconData icon;

  const _ValueListPickerWidget({
    required this.label,
    required this.colorScheme,
    required this.optionsLoader,
    required this.fillMappings,
    required this.icon,
  });

  @override
  State<_ValueListPickerWidget> createState() => _ValueListPickerWidgetState();
}

class _ValueListPickerWidgetState extends State<_ValueListPickerWidget> {
  bool _loading = false;

  Future<void> _open() async {
    setState(() => _loading = true);
    List<Map<String, dynamic>> options = const [];
    try {
      options = await widget.optionsLoader();
    } finally {
      setState(() => _loading = false);
    }

    final cs = widget.colorScheme;
    await showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: cs.surface,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) {
        return SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: options.isEmpty
                ? Center(
                    child: Text('No data',
                        style: TextStyle(color: cs.onSurfaceVariant)))
                : ListView.separated(
                    itemCount: options.length,
                    separatorBuilder: (_, __) =>
                        Divider(height: 1, color: cs.outline.withOpacity(0.08)),
                    itemBuilder: (context, index) {
                      final o = options[index];
                      return ListTile(
                        leading: CircleAvatar(
                            child: Text(
                                ((o['name'] ?? o['title'] ?? 'N') as String)
                                    .substring(0, 1)
                                    .toUpperCase())),
                        title: Text((o['name'] ?? o['title'] ?? '').toString()),
                        subtitle: Text(
                            (o['description'] ?? o['email'] ?? o['phone'] ?? '')
                                .toString()),
                        onTap: () {
                          final scope = EntityFormScope.of(context);
                          if (scope != null) {
                            widget.fillMappings
                                .forEach((sourceKey, targetFieldKey) {
                              final v = o[sourceKey];
                              final c = scope.controllers[targetFieldKey];
                              if (c != null) c.text = v?.toString() ?? '';
                            });
                            scope.notifyParent();
                          }
                          Navigator.of(context).pop();
                        },
                      );
                    },
                  ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final cs = widget.colorScheme;
    return Row(
      children: [
        Expanded(
          child: Text(widget.label,
              style:
                  TextStyle(color: cs.onSurface, fontWeight: FontWeight.w600)),
        ),
        IconButton(
          tooltip: 'Open ${widget.label}',
          icon: _loading
              ? const SizedBox(
                  width: 18,
                  height: 18,
                  child: CircularProgressIndicator(strokeWidth: 2))
              : Icon(widget.icon, color: cs.primary),
          onPressed: _loading ? null : _open,
        )
      ],
    );
  }
}
