import { Linking, Platform } from 'react-native';
import { whatsappPhoneDigits } from './whatsappLocal';

export type MapAppId = 'apple' | 'google' | 'waze';

function coordsOk(lat: number, lng: number): boolean {
  return Number.isFinite(lat) && Number.isFinite(lng);
}

/** Open a specific navigation app with destination. */
export async function openWithMapApp(
  app: MapAppId,
  lat: number,
  lng: number,
  label?: string | null,
): Promise<void> {
  if (!coordsOk(lat, lng)) return;
  const title = encodeURIComponent((label || '').trim() || `${lat},${lng}`);

  const urls: Record<MapAppId, string[]> = {
    apple: [
      `maps://?daddr=${lat},${lng}&q=${title}`,
      `http://maps.apple.com/?daddr=${lat},${lng}&q=${title}`,
    ],
    google: [
      `comgooglemaps://?daddr=${lat},${lng}&directionsmode=driving`,
      `https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`,
    ],
    waze: [
      `waze://?ll=${lat},${lng}&navigate=yes`,
      `https://waze.com/ul?ll=${lat},${lng}&navigate=yes`,
    ],
  };

  for (const url of urls[app]) {
    try {
      if (url.startsWith('http')) {
        await Linking.openURL(url);
        return;
      }
      if (await Linking.canOpenURL(url)) {
        await Linking.openURL(url);
        return;
      }
    } catch {
      // try next
    }
  }
}

/**
 * Fallback when no picker UI: prefer OS geo / Apple Maps, else Google.
 * Prefer {@link MapAppPickerSheet} for explicit user choice.
 */
export async function openMapLocation(
  lat: number,
  lng: number,
  label?: string | null,
): Promise<void> {
  if (!coordsOk(lat, lng)) return;
  if (Platform.OS === 'ios') {
    await openWithMapApp('apple', lat, lng, label);
    return;
  }
  const title = encodeURIComponent((label || '').trim() || `${lat},${lng}`);
  const geo = `geo:${lat},${lng}?q=${lat},${lng}(${title})`;
  try {
    if (await Linking.canOpenURL(geo)) {
      await Linking.openURL(geo);
      return;
    }
  } catch {
    // fall through
  }
  await openWithMapApp('google', lat, lng, label);
}

/** Open WhatsApp chat with this client (no message prefill). */
export async function openWhatsAppNumber(phone: string): Promise<void> {
  const digits = whatsappPhoneDigits(phone);
  if (!digits) return;
  const appUrl = `whatsapp://send?phone=${digits}`;
  try {
    if (await Linking.canOpenURL(appUrl)) {
      await Linking.openURL(appUrl);
      return;
    }
  } catch {
    // fall through
  }
  await Linking.openURL(`https://wa.me/${digits}`);
}

/**
 * Best-effort WhatsApp voice call.
 * Official call deep links are unreliable — try call scheme, then open the chat
 * so the user can tap the call button in WhatsApp.
 */
export async function openWhatsAppCall(phone: string): Promise<void> {
  const digits = whatsappPhoneDigits(phone);
  if (!digits) return;
  const candidates = [
    `whatsapp://call?phone=${digits}`,
    `https://wa.me/call/${digits}`,
  ];
  for (const url of candidates) {
    try {
      if (url.startsWith('http') || (await Linking.canOpenURL(url))) {
        await Linking.openURL(url);
        return;
      }
    } catch {
      // try next
    }
  }
  await openWhatsAppNumber(phone);
}
