import 'package:flutter/material.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import '../../../../domain/services/qr/qr_scanner.dart';

class AddContactButton extends StatelessWidget {
  const AddContactButton({super.key});

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.add, color: Colors.blue),
      onPressed: () {
        showDialog(
          context: context,
          barrierDismissible: true, // Allows dismissal by tapping outside
          builder: (BuildContext context) {
            return AlertDialog(
              backgroundColor: Colors.black,
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextButton(
                    onPressed: () async {
                      Navigator.of(context).pop(); // close dialog

                      // Go to QR Scanner
                      final vCardString = await Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const QRCodeScannerScreen(),
                        ),
                      );

                      if (vCardString != null && vCardString is String) {
                        await FlutterContacts.openExternalInsert(Contact
                            .fromVCard(vCardString));
                      }
                    },
                    child: const Text(
                      "Scan QR code",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  TextButton(
                    onPressed: () async {
                      Navigator.of(context).pop();
                      // Create a blank contact entry
                      await FlutterContacts.openExternalInsert();
                    },
                    child: const Text(
                      "Create new contact",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }
}
