import 'package:flutter/material.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:mypoint_flutter_app/core/theme/base_color.dart';

/// Mở bottom sheet hiển thị danh sách danh bạ để chọn
Future<Contact?> showContactPicker(BuildContext context) async {
  final granted = await FlutterContacts.requestPermission();
  if (!granted) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Không có quyền truy cập danh bạ')),
    );
    return null;
  }

  // Lấy contacts (kèm số điện thoại)
  final contacts = await FlutterContacts.getContacts(
    withProperties: true,
    withPhoto: false,
  );

  if (contacts.isEmpty) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Không có danh bạ nào')),
    );
    return null;
  }

  // Mở bottom sheet để user chọn
  return showModalBottomSheet<Contact>(
    context: context,
    isScrollControlled: true,
    backgroundColor: Colors.white,
    shape: const RoundedRectangleBorder(
      borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
    ),
    builder: (_) => _ContactPickerSheet(contacts: contacts),
  );
}

class _ContactPickerSheet extends StatefulWidget {
  final List<Contact> contacts;
  const _ContactPickerSheet({required this.contacts});

  @override
  State<_ContactPickerSheet> createState() => _ContactPickerSheetState();
}

class _ContactPickerSheetState extends State<_ContactPickerSheet> {
  late List<Contact> _filtered;
  final _searchCtrl = TextEditingController();

  @override
  void initState() {
    super.initState();
    _filtered = widget.contacts;
    _searchCtrl.addListener(_onSearchChanged);
  }

  @override
  void dispose() {
    _searchCtrl.removeListener(_onSearchChanged);
    _searchCtrl.dispose();
    super.dispose();
  }

  void _onSearchChanged() {
    final q = _searchCtrl.text.trim().toLowerCase();
    if (q.isEmpty) {
      setState(() => _filtered = widget.contacts);
    } else {
      setState(() {
        _filtered = widget.contacts.where((c) {
          final name = c.displayName.toLowerCase();
          final phones = c.phones.map((e) => e.number).join(' ').toLowerCase();
          return name.contains(q) || phones.contains(q);
        }).toList();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final bottomInset = MediaQuery.of(context).viewInsets.bottom;
    return SafeArea(
      top: false,
      child: Padding(
        padding: EdgeInsets.only(bottom: bottomInset),
        child: SizedBox(
          height: MediaQuery.of(context).size.height * 0.75,
          child: Column(
            children: [
              const SizedBox(height: 8),
              Container(width: 40, height: 4, decoration: BoxDecoration(color: Colors.black26, borderRadius: BorderRadius.circular(2))),
              const SizedBox(height: 12),
              const Text('Chọn liên hệ', style: TextStyle(fontWeight: FontWeight.w700, fontSize: 18)),
              const SizedBox(height: 8),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: TextField(
                  controller: _searchCtrl,
                  decoration: InputDecoration(
                    hintText: 'Tìm tên hoặc số',
                    prefixIcon: const Icon(Icons.search),
                    contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                    border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Colors.grey.shade400, width: 1),),
                  ),
                ),
              ),
              const SizedBox(height: 8),
              Expanded(
                child: ListView.separated(
                  itemCount: _filtered.length,
                  separatorBuilder: (_, _) => const Divider(height: 1),
                  itemBuilder: (context, index) {
                    final c = _filtered[index];
                    final subtitle = c.phones.isNotEmpty ? c.phones.first.number : 'Không có số';
                    return ListTile(
                      leading: CircleAvatar(
                          backgroundColor: BaseColor.primary400,
                          child: Text(c.displayName.isNotEmpty ? c.displayName[0].toUpperCase() : '?'), // màu nền cho avatar
                      ),
                      title: Text(c.displayName),
                      subtitle: Text(subtitle),
                      onTap: () => Navigator.of(context).pop<Contact>(c), // trả về contact
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

