import 'package:flutter/foundation.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../widgets/custom_empty_widget.dart';
import '../../../widgets/custom_search_navigation_bar.dart';
import '../../resources/base_color.dart';
import '../invite_friend_campaign/invite_friend_campaign_viewmodel.dart';

class ContactsListScreen extends StatefulWidget {
  const ContactsListScreen({super.key});

  @override
  _ContactsListScreenState createState() => _ContactsListScreenState();
}

class _ContactsListScreenState extends State<ContactsListScreen> {
  final InviteFriendCampaignViewModel viewModel = Get.put(InviteFriendCampaignViewModel());

  List<Contact> contacts = [];
  List<Contact> displayContacts = [];
  String searchQuery = '';

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    if (args is Map) {
      contacts = args['contacts'];
    }
    displayContacts = contacts;
    viewModel.phoneInviteFriendResponse = (sms, phone) {
      _openSMS(sms, phone);
    };
  }

  Future<void> _openSMS(String sms, String phone) async {
    final uri = Uri(scheme: 'sms', path: phone, queryParameters: <String, String>{'body': sms});

    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    }
  }

  void _onSearchChanged(String query) {
    setState(() {
      displayContacts = searchContacts(query);
    });
  }

  List<Contact> searchContacts(String query) {
    query = query.trim();
    if (query.isEmpty) return contacts;
    final isNumber = RegExp(r'^\d+$').hasMatch(query);
    return contacts.where((contact) {
      final name = contact.displayName?.toLowerCase() ?? '';
      final phone =
          contact.phones?.isNotEmpty == true ? contact.phones!.first.number?.replaceAll(RegExp(r'\D'), '') ?? '' : '';
      if (isNumber) {
        return phone.contains(query);
      } else {
        return name.contains(query.toLowerCase());
      }
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomSearchNavigationBar(onSearchChanged: _onSearchChanged),
      body:
          displayContacts.isEmpty
              ? EmptyWidget(size: Size(240, 240))
              : ListView.builder(
                physics: const AlwaysScrollableScrollPhysics(),
                itemCount: displayContacts.length,
                itemBuilder: (context, index) {
                  final contact = displayContacts[index];
                  return GestureDetector(
                    onTap: () {
                      debugPrint('contact selected ${contact.phones.firstOrNull}');
                    },
                    child: Column(
                      children: [
                        _buildContactCard(contact),
                        Padding(
                          padding: const EdgeInsets.only(left: 20, right: 20),
                          child: const Divider(height: 1, color: Colors.black12),
                        ),
                      ],
                    ),
                  );
                },
              ),
    );
  }

  Widget _buildContactCard(Contact contact) {
    final name = contact.displayName;
    final phone = contact.phones?.isNotEmpty == true ? contact.phones?.first.number ?? 'Không số' : 'Không số';
    return ListTile(
      leading: CircleAvatar(
        backgroundImage: const AssetImage('assets/images/ic_pipi_02.png'),
        backgroundColor: BaseColor.primary200,
      ),
      title: Text(name, style: const TextStyle(fontWeight: FontWeight.bold)),
      subtitle: Text(phone),
      trailing: OutlinedButton(
        style: OutlinedButton.styleFrom(
          side: const BorderSide(color: Colors.red, width: 1.5),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        ),
        onPressed: () {
          viewModel.phoneInviteFriend(phone);
        },
        child: const Text('Mời', style: TextStyle(color: Colors.red, fontWeight: FontWeight.w800)),
      ),
    );
  }
}
