import 'package:flutter/material.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../services/contact_service.dart';
import '../../services/obfuscate_service.dart'; // Import ObfuscateService
import '../../services/call_service.dart'; // Import the CallService
import '../contacts/widgets/add_contact_button.dart';

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

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

class _CompositionPageState extends State<CompositionPage> {
  String dialedNumber = "";
  List<Contact> _allContacts = [];
  List<Contact> _filteredContacts = [];
  final ContactService _contactService = ContactService();

  // Instantiate the ObfuscateService
  final ObfuscateService _obfuscateService = ObfuscateService();

  // Instantiate the CallService
  final CallService _callService = CallService();

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

  Future<void> _fetchContacts() async {
    _allContacts = await _contactService.fetchContacts();
    _filteredContacts = _allContacts;
    setState(() {});
  }

  void _filterContacts() {
    setState(() {
      _filteredContacts = _allContacts.where((contact) {
        final phoneMatch = contact.phones.any((phone) =>
            phone.number.replaceAll(RegExp(r'\D'), '').contains(dialedNumber));
        final nameMatch = contact.displayName
            .toLowerCase()
            .contains(dialedNumber.toLowerCase());
        return phoneMatch || nameMatch;
      }).toList();
    });
  }

  void _onNumberPress(String number) {
    setState(() {
      dialedNumber += number;
      _filterContacts();
    });
  }

  void _onDeletePress() {
    setState(() {
      if (dialedNumber.isNotEmpty) {
        dialedNumber = dialedNumber.substring(0, dialedNumber.length - 1);
        _filterContacts();
      }
    });
  }

  void _onClearPress() {
    setState(() {
      dialedNumber = "";
      _filteredContacts = _allContacts;
    });
  }

  // Function to call a contact's number using the CallService
  void _makeCall(String phoneNumber) async {
    try {
      await _callService.makeGsmCall(context, phoneNumber: phoneNumber);
      setState(() {
        dialedNumber = phoneNumber;
      });
    } catch (e) {
      debugPrint("Error making call: $e");
    }
  }

  // Function to send an SMS to a contact's number
  void _launchSms(String phoneNumber) async {
    final uri = Uri(scheme: 'sms', path: phoneNumber);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      debugPrint('Could not send SMS to $phoneNumber');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          Column(
            children: [
              // Top half: Display contacts matching dialed number
              Expanded(
                flex: 2,
                child: Container(
                  padding: const EdgeInsets.only(
                      top: 42.0, left: 16.0, right: 16.0, bottom: 16.0),
                  color: Colors.black,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                        child: ListView(
                          children: _filteredContacts.isNotEmpty
                              ? _filteredContacts.map((contact) {
                            final phoneNumber = contact.phones.isNotEmpty
                                ? contact.phones.first.number
                                : 'No phone number';
                            return ListTile(
                              title: Text(
                                _obfuscateService.obfuscateData(contact.displayName),
                                style: const TextStyle(color: Colors.white),
                              ),
                              subtitle: Text(
                                _obfuscateService.obfuscateData(phoneNumber),
                                style: const TextStyle(color: Colors.grey),
                              ),
                              trailing: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  // Call button (Now using CallService)
                                  IconButton(
                                    icon: Icon(Icons.phone,
                                        color: Colors.green[300],
                                        size: 20),
                                    onPressed: () {
                                      _makeCall(phoneNumber); // Make a call using CallService
                                    },
                                  ),
                                  // Message button
                                  IconButton(
                                    icon: Icon(Icons.message,
                                        color: Colors.blue[300],
                                        size: 20),
                                    onPressed: () {
                                      _launchSms(phoneNumber);
                                    },
                                  ),
                                ],
                              ),
                              onTap: () {
                                // Handle contact selection if needed
                              },
                            );
                          }).toList()
                              : [],
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              // Bottom half: Dialpad and Dialed number display with erase button
              Expanded(
                flex: 2,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      // Display dialed number with erase button
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: Align(
                              alignment: Alignment.center,
                              child: Text(
                                dialedNumber,
                                style: const TextStyle(
                                    fontSize: 24, color: Colors.white),
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ),
                          IconButton(
                            onPressed: _onClearPress,
                            icon: const Icon(Icons.backspace,
                                color: Colors.white),
                          ),
                        ],
                      ),
                      const SizedBox(height: 10),

                      // Dialpad
                      Expanded(
                        child: SingleChildScrollView(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Row(
                                mainAxisAlignment:
                                MainAxisAlignment.spaceEvenly,
                                children: [
                                  _buildDialButton('1'),
                                  _buildDialButton('2'),
                                  _buildDialButton('3'),
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                MainAxisAlignment.spaceEvenly,
                                children: [
                                  _buildDialButton('4'),
                                  _buildDialButton('5'),
                                  _buildDialButton('6'),
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                MainAxisAlignment.spaceEvenly,
                                children: [
                                  _buildDialButton('7'),
                                  _buildDialButton('8'),
                                  _buildDialButton('9'),
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                MainAxisAlignment.spaceEvenly,
                                children: [
                                  _buildDialButton('*'),
                                  _buildDialButton('0'),
                                  _buildDialButton('#'),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),

          // Add Contact Button
          Positioned(
            bottom: 20.0,
            left: 0,
            right: 0,
            child: Center(
              child: AddContactButton(),
            ),
          ),

          // Top Row with Back Arrow
          Positioned(
            top: 40.0,
            left: 16.0,
            child: IconButton(
              icon: const Icon(Icons.arrow_back, color: Colors.white),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDialButton(String number) {
    return ElevatedButton(
      onPressed: () => _onNumberPress(number),
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.black,
        shape: const CircleBorder(),
        padding: const EdgeInsets.all(16),
      ),
      child: Text(
        number,
        style: const TextStyle(
          fontSize: 24,
          color: Colors.white,
        ),
      ),
    );
  }
}
