import { Linking, Platform } from 'react-native';
import * as Clipboard from 'expo-clipboard';
import * as FileSystem from 'expo-file-system/legacy';
import * as Sharing from 'expo-sharing';
import { normalizePhoneInput, splitPhoneForStorage } from './phone';

/** Digits only with country code (Tunisia 216 by default when local 8 digits). */
export function whatsappPhoneDigits(phone?: string | null): string {
  if (!phone) return '';
  const split = splitPhoneForStorage('', phone);
  if (split.digits) return split.digits;
  return normalizePhoneInput(phone);
}

async function openWhatsAppChat(phone: string, message: string): Promise<void> {
  const text = message.trim();
  const appUrl = text
    ? `whatsapp://send?phone=${phone}&text=${encodeURIComponent(text)}`
    : `whatsapp://send?phone=${phone}`;
  const webUrl = text
    ? `https://wa.me/${phone}?text=${encodeURIComponent(text)}`
    : `https://wa.me/${phone}`;

  try {
    if (await Linking.canOpenURL(appUrl)) {
      await Linking.openURL(appUrl);
      return;
    }
  } catch {
    // fall through to wa.me
  }
  await Linking.openURL(webUrl);
}

/**
 * Open WhatsApp on the client’s chat (phone + message), then offer the PDF
 * via the system share sheet so the user can attach it in that conversation.
 */
export async function openLocalWhatsAppWithPdf(opts: {
  phone?: string | null;
  message: string;
  pdfBase64: string;
  filename: string;
}): Promise<{ messageCopied: boolean; phone: string }> {
  return openLocalWhatsAppWithPdfs({
    phone: opts.phone,
    message: opts.message,
    pdfs: [{ base64: opts.pdfBase64, filename: opts.filename }],
  });
}

/**
 * Same as openLocalWhatsAppWithPdf but for several PDFs (CRM parity: bien + projet…).
 * Opens WhatsApp once, then presents each PDF share sheet in order.
 */
export async function openLocalWhatsAppWithPdfs(opts: {
  phone?: string | null;
  message: string;
  pdfs: Array<{ base64: string; filename: string }>;
}): Promise<{ messageCopied: boolean; phone: string }> {
  const message = opts.message.trim();
  const phone = whatsappPhoneDigits(opts.phone);
  if (!phone) {
    throw new Error('Numéro client manquant.');
  }
  const pdfs = opts.pdfs.filter((p) => p?.base64);
  if (pdfs.length === 0) {
    throw new Error('Aucun PDF à joindre.');
  }

  const dir = FileSystem.cacheDirectory ?? FileSystem.documentDirectory;
  if (!dir) {
    throw new Error('Stockage local indisponible.');
  }

  const paths: string[] = [];
  for (let i = 0; i < pdfs.length; i++) {
    const pdf = pdfs[i];
    const safeName = (pdf.filename || `document_${i + 1}.pdf`).replace(/[^\w.\-]+/g, '_');
    const path = `${dir}${safeName.endsWith('.pdf') ? safeName : `${safeName}.pdf`}`;
    await FileSystem.writeAsStringAsync(path, pdf.base64, {
      encoding: FileSystem.EncodingType.Base64,
    });
    paths.push(path);
  }

  let messageCopied = false;
  if (message) {
    await Clipboard.setStringAsync(message);
    messageCopied = true;
  }

  // 1) Open WhatsApp directly on this client’s number
  await openWhatsAppChat(phone, message);

  // 2) Share each PDF so the user can attach them in WhatsApp (same files as CRM)
  const canShare = await Sharing.isAvailableAsync();
  if (canShare) {
    await new Promise((r) => setTimeout(r, 600));
    for (let i = 0; i < paths.length; i++) {
      await Sharing.shareAsync(paths[i], {
        mimeType: 'application/pdf',
        dialogTitle:
          Platform.OS === 'android'
            ? `Joindre le PDF (${i + 1}/${paths.length})`
            : `Joindre le PDF à WhatsApp (${i + 1}/${paths.length})`,
        UTI: 'com.adobe.pdf',
      });
      if (i < paths.length - 1) {
        await new Promise((r) => setTimeout(r, 400));
      }
    }
  }

  return { messageCopied, phone };
}

/** Text-only local WhatsApp — opens the client chat when a phone is known. */
export async function openLocalWhatsAppText(opts: {
  phone?: string | null;
  message: string;
}): Promise<void> {
  const message = opts.message.trim();
  const phone = whatsappPhoneDigits(opts.phone);
  if (!message) {
    throw new Error('Message vide.');
  }
  if (phone) {
    await openWhatsAppChat(phone, message);
    return;
  }
  await Clipboard.setStringAsync(message);
  if (await Linking.canOpenURL('whatsapp://send')) {
    await Linking.openURL('whatsapp://send');
    return;
  }
  throw new Error("WhatsApp n'est pas installé.");
}
