import 'package:dialer/presentation/features/home/home_page.dart';
import 'package:dialer/presentation/features/home/default_dialer_prompt.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import 'core/config/app_config.dart';
import 'domain/services/call_service.dart';
import 'domain/services/cryptography/asymmetric_crypto_service.dart';
import 'presentation/features/contacts/contact_state.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize app configuration
  await AppConfig.initialize();

  // Initialize cryptography service with error handling
  final AsymmetricCryptoService cryptoService = AsymmetricCryptoService();
  try {
    await cryptoService.initializeDefaultKeyPair();
  } catch (e) {
    debugPrint('Error initializing cryptography: $e');
    // Continue app initialization even if crypto fails
  }

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

  // Initialize call service
  CallService();

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

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 DialerApp extends StatelessWidget {
  const DialerApp({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(
        title: 'Dialer App',
        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()),
        },
      ),
    );
  }
}