import 'package:flutter/material.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../common/widgets/username_color_generator.dart';
import '../../../common/widgets/color_darkener.dart';
import '../../../../domain/services/obfuscate_service.dart';
import '../../../../domain/services/block_service.dart';
import '../../../../domain/services/contact_service.dart';
import '../../../../domain/services/call_service.dart';

class ContactModal extends StatefulWidget {
  final Contact contact;
  final Function onEdit;
  final Function onToggleFavorite;
  final bool isFavorite;

  const ContactModal({
    super.key,
    required this.contact,
    required this.onEdit,
    required this.onToggleFavorite,
    required this.isFavorite,
  });

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

class _ContactModalState extends State<ContactModal> {
  late String phoneNumber;
  bool isBlocked = false;
  final ObfuscateService _obfuscateService = ObfuscateService();
  final CallService _callService = CallService();
  final ContactService _contactService = ContactService();

  @override
  void initState() {
    super.initState();
    phoneNumber = widget.contact.phones.isNotEmpty
        ? widget.contact.phones.first.number
        : 'No phone number';
    _checkIfBlocked();
  }

  Future<void> _checkIfBlocked() async {
    if (phoneNumber != 'No phone number') {
      bool blocked = await BlockService().isNumberBlocked(phoneNumber);
      if (mounted) {
        setState(() {
          isBlocked = blocked;
        });
      }
    }
  }

  Future<void> _toggleBlockState() async {
    if (phoneNumber == 'No phone number') {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('No phone number to block or unblock')),
      );
      return;
    }

    if (isBlocked) {
      await BlockService().unblockNumber(phoneNumber);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('$phoneNumber has been unblocked')),
        );
      }
    } else {
      await BlockService().blockNumber(phoneNumber);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('$phoneNumber has been blocked')),
        );
      }
    }

    if (phoneNumber != 'No phone number' && mounted) {
      _checkIfBlocked();
    }

    if (mounted) {
      Navigator.of(context).pop();
    }
  }

  void _launchSms(String phoneNumber) async {
    final uri = Uri(scheme: 'sms', path: phoneNumber);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      debugPrint('Could not launch SMS to $phoneNumber');
    }
  }

  void _launchEmail(String email) async {
    final uri = Uri(scheme: 'mailto', path: email);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      debugPrint('Could not launch email to $email');
    }
  }

  void _deleteContact() async {
    final bool shouldDelete = await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Delete Contact'),
        content: Text(
            'Are you sure you want to delete ${_obfuscateService.obfuscateData(widget.contact.displayName)}?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('Delete'),
          ),
        ],
      ),
    );

    if (shouldDelete && mounted) {
      try {
        // Delete the contact
        await FlutterContacts.deleteContact(widget.contact);

        // Show success message
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
                content: Text(
                    '${_obfuscateService.obfuscateData(widget.contact.displayName)} deleted')),
          );

          // Close the modal
          Navigator.of(context).pop();
        }
      } catch (e) {
        // Handle errors and show a failure message
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
                content:
                    Text('Failed to delete ${widget.contact.displayName}: $e')),
          );
        }
      }
    }
  }

  void _shareContactAsQRCode() {
    // Use the ContactService to show the QR code for the contact's vCard
    _contactService.showContactQRCodeDialog(context, widget.contact);
  }

  @override
  Widget build(BuildContext context) {
    String email = widget.contact.emails.isNotEmpty
        ? _obfuscateService.obfuscateData(widget.contact.emails.first.address)
        : 'No email';

    final avatarColor = generateColorFromName(widget.contact.displayName);

    return GestureDetector(
      onTap: () => Navigator.of(context).pop(),
      child: Container(
        color: Colors.black.withOpacity(0.5),
        child: GestureDetector(
          onTap: () {},
          child: FractionallySizedBox(
            heightFactor: 0.8,
            child: Container(
              decoration: BoxDecoration(
                color: Colors.grey[900],
                borderRadius:
                    const BorderRadius.vertical(top: Radius.circular(20)),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // Modal Handle and Three-Dot Menu
                  Stack(
                    children: [
                      Align(
                        alignment: Alignment.center,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(vertical: 10),
                          child: Container(
                            width: 50,
                            height: 5,
                            decoration: BoxDecoration(
                              color: Colors.grey.shade300,
                              borderRadius: BorderRadius.circular(5),
                            ),
                          ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.topRight,
                        child: Padding(
                          padding: const EdgeInsets.only(top: 10, right: 10),
                          child: PopupMenuButton<String>(
                            icon: const Icon(Icons.more_vert,
                                color: Colors.white),
                            onSelected: (String choice) {
                              if (choice == 'delete') {
                                _deleteContact();
                              } else if (choice == 'share') {
                                _shareContactAsQRCode();
                              }
                              // Handle other choices if needed
                            },
                            itemBuilder: (BuildContext context) {
                              return [
                                const PopupMenuItem<String>(
                                  value: 'delete',
                                  child: Text('Delete'),
                                ),
                                const PopupMenuItem<String>(
                                  value: 'share',
                                  child: Text('Share (via QR code)'),
                                ),
                              ];
                            },
                          ),
                        ),
                      ),
                    ],
                  ),
                  // Contact Profile
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      children: [
                        widget.contact.thumbnail != null && widget.contact.thumbnail!.isNotEmpty
                            ? ClipOval(
                                child: Image.memory(
                                  widget.contact.thumbnail!,
                                  fit: BoxFit.cover,
                                  width: 100,
                                  height: 100,
                                ),
                              )
                            : CircleAvatar(
                                backgroundColor: avatarColor,
                                radius: 50,
                                child: Text(
                                  widget.contact.displayName.isNotEmpty
                                      ? widget.contact.displayName[0].toUpperCase()
                                      : '?',
                                  style: TextStyle(
                                    color: darken(avatarColor),
                                    fontSize: 40,
                                  ),
                                ),
                              ),
                        const SizedBox(height: 10),
                        Text(
                          _obfuscateService
                              .obfuscateData(widget.contact.displayName),
                          style: const TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                              color: Colors.white),
                        ),
                      ],
                    ),
                  ),
                  const Divider(color: Colors.grey),
                  // Contact Actions
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          ListTile(
                            leading: const Icon(Icons.phone, color: Colors.green),
                            title: Text(
                              _obfuscateService.obfuscateData(phoneNumber),
                              style: const TextStyle(color: Colors.white),
                            ),
                            onTap: () async {
                              if (widget.contact.phones.isNotEmpty) {
                                await _callService.makeGsmCall(context,
                                    phoneNumber: phoneNumber);
                              }
                            },
                          ),
                          ListTile(
                            leading: const Icon(Icons.message, color: Colors.blue),
                            title: Text(
                              _obfuscateService.obfuscateData(phoneNumber),
                              style: const TextStyle(color: Colors.white),
                            ),
                            onTap: () {
                              if (widget.contact.phones.isNotEmpty) {
                                _launchSms(phoneNumber);
                              }
                            },
                          ),
                          ListTile(
                            leading: const Icon(Icons.email, color: Colors.orange),
                            title: Text(
                              email,
                              style: const TextStyle(color: Colors.white),
                            ),
                            onTap: () {
                              if (widget.contact.emails.isNotEmpty) {
                                _launchEmail(email);
                              }
                            },
                          ),
                          const Divider(color: Colors.grey),
                          // Favorite, Edit, and Block/Unblock Buttons
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 16.0),
                            child: Column(
                              children: [
                                // Favorite button
                                SizedBox(
                                  width: double.infinity,
                                  child: ElevatedButton.icon(
                                    onPressed: () {
                                      // First close the modal to avoid unmounted widget issues
                                      Navigator.of(context).pop();
                                      // Then toggle the favorite status
                                      widget.onToggleFavorite();
                                    },
                                    icon: Icon(widget.isFavorite
                                        ? Icons.star
                                        : Icons.star_border),
                                    label: Text(
                                        widget.isFavorite ? 'Unfavorite' : 'Favorite'),
                                  ),
                                ),
                                const SizedBox(height: 10),
                                // Edit button
                                SizedBox(
                                  width: double.infinity,
                                  child: ElevatedButton.icon(
                                    onPressed: () => widget.onEdit(),
                                    icon: const Icon(Icons.edit),
                                    label: const Text('Edit Contact'),
                                  ),
                                ),
                                const SizedBox(height: 10),
                                // Block/Unblock button
                                SizedBox(
                                  width: double.infinity,
                                  child: ElevatedButton.icon(
                                    onPressed: _toggleBlockState,
                                    icon: Icon(
                                        isBlocked ? Icons.block : Icons.block_flipped),
                                    label: Text(isBlocked ? 'Unblock' : 'Block'),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 16),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
