import 'package:flutter/material.dart';

import 'marketing_ui.dart';

/// A searchable service-center selector that stays responsive with large lists.
/// Search scans the local center list; ListView.builder only builds visible rows.
class MarketingSearchableCenterDropdown extends StatelessWidget {
  const MarketingSearchableCenterDropdown({
    super.key,
    required this.centers,
    required this.value,
    required this.onChanged,
    this.label = 'Service center',
  });

  final List<Map<String, dynamic>> centers;
  final int value;
  final ValueChanged<int> onChanged;
  final String label;

  String _name(Map<String, dynamic> center) =>
      '${center['center_name'] ?? 'Service center'}';

  String _campus(Map<String, dynamic> center) =>
      '${center['campus_name'] ?? 'Campus not set'}';

  String _code(Map<String, dynamic> center) =>
      '${center['center_code'] ?? ''}';

  @override
  Widget build(BuildContext context) {
    final selected = centers.where((center) => marketingNumber(center['id']) == value);
    final selectedCenter = selected.isEmpty ? null : selected.first;
    return InkWell(
      onTap: centers.isEmpty ? null : () => _chooseCenter(context),
      child: InputDecorator(
        decoration: InputDecoration(
          labelText: label,
          isDense: true,
          filled: true,
          fillColor: Colors.white,
          suffixIcon: const Icon(Icons.search, color: marketingGreen),
          border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
          enabledBorder: const OutlineInputBorder(
            borderRadius: BorderRadius.zero,
            borderSide: BorderSide(color: marketingLine),
          ),
        ),
        child: Text(
          selectedCenter == null
              ? 'Choose a service center'
              : '${_campus(selectedCenter)}  •  ${_name(selectedCenter)}',
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: const TextStyle(color: marketingInk, fontSize: 14),
        ),
      ),
    );
  }

  Future<void> _chooseCenter(BuildContext context) async {
    final chosen = await showDialog<int>(
      context: context,
      builder: (dialogContext) => _CenterSearchDialog(
        centers: centers,
        selectedId: value,
        name: _name,
        campus: _campus,
        code: _code,
      ),
    );
    if (chosen != null) onChanged(chosen);
  }
}

class _CenterSearchDialog extends StatefulWidget {
  const _CenterSearchDialog({
    required this.centers,
    required this.selectedId,
    required this.name,
    required this.campus,
    required this.code,
  });

  final List<Map<String, dynamic>> centers;
  final int selectedId;
  final String Function(Map<String, dynamic>) name;
  final String Function(Map<String, dynamic>) campus;
  final String Function(Map<String, dynamic>) code;

  @override
  State<_CenterSearchDialog> createState() => _CenterSearchDialogState();
}

class _CenterSearchDialogState extends State<_CenterSearchDialog> {
  final TextEditingController _search = TextEditingController();
  String _query = '';

  List<Map<String, dynamic>> get _matches {
    final query = _query.trim().toLowerCase();
    if (query.isEmpty) return widget.centers;
    return widget.centers.where((center) {
      final searchable =
          '${widget.name(center)} ${widget.campus(center)} ${widget.code(center)} ${center['location'] ?? ''}'
              .toLowerCase();
      return searchable.contains(query);
    }).toList(growable: false);
  }

  @override
  void dispose() {
    _search.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final screen = MediaQuery.sizeOf(context);
    final matches = _matches;
    return Dialog(
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      insetPadding: const EdgeInsets.all(16),
      child: SizedBox(
        width: screen.width < 600 ? screen.width - 32 : 520,
        height: screen.height < 560 ? screen.height - 32 : 500,
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.fromLTRB(18, 16, 12, 14),
              decoration: const BoxDecoration(
                color: marketingGreenDark,
                border: Border(bottom: BorderSide(color: Color(0xFFD6B45C), width: 3)),
              ),
              child: Row(children: [
                const Icon(Icons.storefront_outlined, color: Colors.white),
                const SizedBox(width: 10),
                const Expanded(
                  child: Text('Select service center',
                      style: TextStyle(color: Colors.white, fontWeight: FontWeight.w800, fontSize: 16)),
                ),
                IconButton(
                  tooltip: 'Close',
                  onPressed: () => Navigator.pop(context),
                  icon: const Icon(Icons.close, color: Colors.white),
                ),
              ]),
            ),
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 14, 16, 8),
              child: TextField(
                controller: _search,
                autofocus: true,
                onChanged: (text) => setState(() => _query = text),
                decoration: const InputDecoration(
                  hintText: 'Search center, campus, code, or location',
                  prefixIcon: Icon(Icons.search, color: marketingGreen),
                  isDense: true,
                  filled: true,
                  fillColor: marketingCanvas,
                  border: OutlineInputBorder(borderRadius: BorderRadius.zero),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.zero,
                    borderSide: BorderSide(color: marketingLine),
                  ),
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 4),
              child: Align(
                alignment: Alignment.centerLeft,
                child: Text('${matches.length} ${matches.length == 1 ? 'center' : 'centers'}',
                    style: const TextStyle(color: marketingMuted, fontSize: 12)),
              ),
            ),
            const Divider(height: 1, color: marketingLine),
            Expanded(
              child: matches.isEmpty
                  ? const Center(child: Text('No service centers match your search.', style: TextStyle(color: marketingMuted)))
                  : ListView.builder(
                      keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
                      itemCount: matches.length,
                      itemBuilder: (context, index) {
                        final center = matches[index];
                        final id = marketingNumber(center['id']);
                        final isSelected = id == widget.selectedId;
                        return ListTile(
                          dense: true,
                          selected: isSelected,
                          selectedTileColor: const Color(0xFFEAF3EE),
                          leading: Icon(isSelected ? Icons.check_circle : Icons.location_on_outlined,
                              color: isSelected ? marketingGreen : marketingMuted, size: 20),
                          title: Text(widget.name(center), maxLines: 1, overflow: TextOverflow.ellipsis,
                              style: const TextStyle(color: marketingInk, fontWeight: FontWeight.w700)),
                          subtitle: Text(
                            '${widget.campus(center)}${widget.code(center).isEmpty ? '' : '  •  ${widget.code(center)}'}',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: const TextStyle(color: marketingMuted, fontSize: 12),
                          ),
                          onTap: () => Navigator.pop(context, id),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }
}
