import 'package:dialer/features/home/home_page.dart';
import 'package:dialer/features/home/default_dialer_prompt.dart';
import 'package:flutter/material.dart';
import 'package:dialer/features/contacts/contact_state.dart';
import 'package:dialer/services/call_service.dart';
import 'package:flutter/services.dart';
import 'globals.dart' as globals;
import 'package:dialer/services/cryptography/asymmetric_crypto_service.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  const stealthFlag = String.fromEnvironment('STEALTH', defaultValue: 'false');
  globals.isStealthMode = stealthFlag.toLowerCase() == 'true';

  final AsymmetricCryptoService cryptoService = AsymmetricCryptoService();
  await cryptoService.initializeDefaultKeyPair();

  // Request permissions before running the app
  await _requestPermissions();

  CallService();

  runApp(
    MultiProvider(
      providers: [
        Provider<AsymmetricCryptoService>(
          create: (_) => cryptoService,
        ),
      ],
      child: Dialer(),
    ),
  );
}

Future<void> _requestPermissions() async {
  Map<Permission, PermissionStatus> statuses = await [
    Permission.phone,
    Permission.contacts,
    Permission.microphone,
  ].request();
  if (statuses.values.every((status) => status.isGranted)) {
    print("All required permissions granted");
    const channel = MethodChannel('call_service');
    await channel.invokeMethod('permissionsGranted');
  } else {
    print("Permissions denied: ${statuses.entries.where((e) => !e.value.isGranted).map((e) => e.key).join(', ')}");
  }
}

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

  Future<bool> _isDefaultDialer() async {
    const channel = MethodChannel('call_service');
    try {
      final isDefault = await channel.invokeMethod<bool>('isDefaultDialer');
      return isDefault ?? false;
    } catch (e) {
      print('Error checking default dialer: $e');
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return ContactState(
      child: MaterialApp(
        navigatorKey: CallService.navigatorKey,
        theme: ThemeData(
          brightness: Brightness.dark,
        ),
        initialRoute: '/',
        routes: {
          '/': (context) => FutureBuilder<bool>(
                future: _isDefaultDialer(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return Scaffold(
                      body: Center(child: CircularProgressIndicator()),
                    );
                  }
                  if (snapshot.hasError || !snapshot.hasData || snapshot.data == false) {
                    return DefaultDialerPromptScreen();
                  }
                  return SafeArea(child: MyHomePage());
                },
              ),
          '/home': (context) => SafeArea(child: MyHomePage()),
        },
      ),
    );
  }
}