import { Share } from "@capacitor/share";

interface ShareOptions {
  title?: string;
  text?: string;
  url: string;
}

export function useShare() {
  const shareViaCapacitor = async ({ title, text, url }: ShareOptions) => {
    try {
      await Share.share({
        title,
        text,
        url,
        dialogTitle: title,
      });
    } catch (error) {
      console.error("Error sharing:", error);
    }
  };

  const shareViaFacebook = (url: string) => {
    const facebookUrl = `https://www.facebook.com/sharer.php?u=${encodeURIComponent(url)}`;
    window.open(facebookUrl, "_blank");
  };

  const shareViaLinkedIn = (url: string, title?: string) => {
    const linkedinUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}&title=${encodeURIComponent(title || "")}`;
    window.open(linkedinUrl, "_blank");
  };

  const shareViaInstagram = (url: string) => {
    // Instagram n'a pas d'API de partage web directe, on redirige vers l'app
    const instagramUrl = `instagram://library?AssetPath=${encodeURIComponent(url)}`;
    window.location.href = instagramUrl;
    
    // Fallback vers le profil Instagram si l'app n'est pas installée
    setTimeout(() => {
      window.location.href = "https://instagram.com";
    }, 2000);
  };

  const shareViaTwitter = (url: string, text?: string) => {
    const twitterUrl = `https://twitter.com/intent/tweet?url=${encodeURIComponent(url)}&text=${encodeURIComponent(text || "")}`;
    window.open(twitterUrl, "_blank");
  };

  const shareViaPinterest = (url: string, text?: string, imageUrl?: string) => {
    const pinterestUrl = `https://pinterest.com/pin/create/button/?url=${encodeURIComponent(url)}&description=${encodeURIComponent(text || "")}${imageUrl ? `&media=${encodeURIComponent(imageUrl)}` : ""}`;
    window.open(pinterestUrl, "_blank");
  };

  const shareViaSMS = (url: string, text?: string) => {
    const smsBody = text ? `${text} ${url}` : url;
    const smsUrl = `sms:?&body=${encodeURIComponent(smsBody)}`;
    window.location.href = smsUrl;
  };

  const share = async (
    network: "facebook" | "linkedin" | "instagram" | "twitter" | "pinterest" | "sms" | "default",
    options: ShareOptions
  ) => {
    const { url, text, title } = options;

    switch (network) {
      case "facebook":
        shareViaFacebook(url);
        break;
      case "linkedin":
        shareViaLinkedIn(url, title);
        break;
      case "instagram":
        shareViaInstagram(url);
        break;
      case "twitter":
        shareViaTwitter(url, text);
        break;
      case "pinterest":
        shareViaPinterest(url, text);
        break;
      case "sms":
        shareViaSMS(url, text);
        break;
      default:
        await shareViaCapacitor(options);
    }
  };

  return {
    share,
  };
}
