import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'package:get/get.dart';
import 'package:siro_driver/views/widgets/error_snakbar.dart';

void showInBrowser(String url) async {
  if (await canLaunchUrl(Uri.parse(url))) {
    launchUrl(Uri.parse(url));
  } else {}
}

String cleanAndFormatPhoneNumber(String phoneNumber) {
  // 1. Clean the number
  String formattedNumber = phoneNumber.replaceAll(RegExp(r'\s+'), '');

  // 2. Format logic (Syria/Egypt/International)
  if (formattedNumber.length > 6) {
    if (formattedNumber.startsWith('09')) {
      formattedNumber = '+963${formattedNumber.substring(1)}';
    } else if (formattedNumber.startsWith('01') && formattedNumber.length == 11) {
      formattedNumber = '+20${formattedNumber.substring(1)}';
    } else if (formattedNumber.startsWith('00')) {
      formattedNumber = '+${formattedNumber.substring(2)}';
    } else if (!formattedNumber.startsWith('+')) {
      formattedNumber = '+$formattedNumber';
    }
  }
  return formattedNumber;
}

Future<void> makePhoneCall(String phoneNumber) async {
  String formattedNumber = cleanAndFormatPhoneNumber(phoneNumber);
  
  if (!formattedNumber.startsWith('+963')) {
    mySnackeBarError("Calling non-Syrian numbers is not supported".tr);
    return;
  }

  // Create URI directly from String to avoid double encoding '+' as '%2B'
  final Uri launchUri = Uri.parse('tel:$formattedNumber');

  // 4. Execute with externalApplication mode
  try {
    if (!await launchUrl(launchUri, mode: LaunchMode.externalApplication)) {
      throw 'Could not launch $launchUri';
    }
  } catch (e) {
    if (await canLaunchUrl(launchUri)) {
      await launchUrl(launchUri);
    } else {
      print("Cannot launch url: $launchUri");
    }
  }
}

void launchCommunication(
    String method, String contactInfo, String message) async {
  String formattedContact = cleanAndFormatPhoneNumber(contactInfo);
  // WhatsApp prefers the phone number without the '+' prefix
  String whatsappContact = formattedContact.replaceAll('+', '');
  String url;

  if (Platform.isIOS) {
    switch (method) {
      case 'phone':
        if (!formattedContact.startsWith('+963')) {
          mySnackeBarError("Calling non-Syrian numbers is not supported".tr);
          return;
        }
        url = 'tel:$formattedContact';
        break;
      case 'sms':
        url = 'sms:$formattedContact?body=${Uri.encodeComponent(message)}';
        break;
      case 'whatsapp':
        url =
            'https://api.whatsapp.com/send?phone=$whatsappContact&text=${Uri.encodeComponent(message)}';
        break;
      case 'email':
        url =
            'mailto:$formattedContact?subject=Subject&body=${Uri.encodeComponent(message)}';
        break;
      default:
        return;
    }
  } else if (Platform.isAndroid) {
    switch (method) {
      case 'phone':
        if (!formattedContact.startsWith('+963')) {
          mySnackeBarError("Calling non-Syrian numbers is not supported".tr);
          return;
        }
        url = 'tel:$formattedContact';
        break;
      case 'sms':
        url = 'sms:$formattedContact?body=${Uri.encodeComponent(message)}';
        break;
      case 'whatsapp':
        final bool whatsappInstalled =
            await canLaunchUrl(Uri.parse('whatsapp://'));
        if (whatsappInstalled) {
          url =
              'whatsapp://send?phone=$whatsappContact&text=${Uri.encodeComponent(message)}';
        } else {
          url =
              'https://api.whatsapp.com/send?phone=$whatsappContact&text=${Uri.encodeComponent(message)}';
        }
        break;
      case 'email':
        url =
            'mailto:$formattedContact?subject=Subject&body=${Uri.encodeComponent(message)}';
        break;
      default:
        return;
    }
  } else {
    return;
  }

  if (await canLaunchUrl(Uri.parse(url))) {
    await launchUrl(Uri.parse(url));
  } else {}
}
