export interface IEmbedProvider {
  id: string;
  name: string;
  regex: RegExp;
  getEmbedUrl: (match: RegExpMatchArray, url?: string) => string;
  getLinkUrl?: (match: RegExpMatchArray, url: string) => string;
  getLabel?: (match: RegExpMatchArray) => string;
}

const GOOGLE_EDITOR_LABELS: Record<string, string> = {
  document: "Google Docs",
  spreadsheets: "Google Sheets",
  presentation: "Google Slides",
};

const googleDrive: Pick<IEmbedProvider, "regex" | "getEmbedUrl" | "getLabel"> = {
  regex:
    /^(?:(?:https?:)?\/\/)?(?:(?:www|m)\.)?(?:drive\.google\.com\/file|docs\.google\.com\/(document|spreadsheets|presentation))(?:\/u\/\d+)?\/d\/(e\/)?([\w-]+)(?:\/(\w+))?/,
  getEmbedUrl: (match, url: string) => {
    const [, editor, published, id, page] = match;
    // Google refuses to frame a published presentation's /pub page.
    if (editor === "presentation" && page === "pub") {
      return url.replace(`${id}/pub`, `${id}/embed`);
    }
    if (published || ["pub", "pubhtml", "embed"].includes(page)) {
      return url;
    }

    const { searchParams, hash } = new URL(url, "https://docs.google.com");
    const resourceKey = searchParams.get("resourcekey");
    const previewUrl = editor
      ? `https://docs.google.com/${editor}/d/${id}/preview`
      : `https://drive.google.com/file/d/${id}/preview`;
    return resourceKey
      ? `${previewUrl}?resourcekey=${encodeURIComponent(resourceKey)}${hash}`
      : `${previewUrl}${hash}`;
  },
  getLabel: (match) => GOOGLE_EDITOR_LABELS[match[1]] ?? "Google Drive",
};

function getYoutubeLinkUrl(
  [, playerPath, videoId]: RegExpMatchArray,
  url: string,
): string {
  if (!playerPath) return url;

  const { searchParams, hash } = new URL(url, "https://www.youtube.com");
  const list = searchParams.get("list");
  if (videoId === "videoseries") {
    return list
      ? `https://www.youtube.com/playlist?${new URLSearchParams({ list })}`
      : url;
  }
  if (videoId === "live_stream") {
    const channel = searchParams.get("channel");
    return channel
      ? `https://www.youtube.com/channel/${encodeURIComponent(channel)}/live`
      : url;
  }

  const params = new URLSearchParams({ v: videoId });
  if (list) params.set("list", list);
  const index = searchParams.get("index");
  if (index) params.set("index", index);
  const start =
    searchParams.get("start") ||
    searchParams.get("t") ||
    new URLSearchParams(hash.slice(1)).get("t");
  if (start) params.set("t", start);
  return `https://www.youtube.com/watch?${params}`;
}

export const embedProviders: IEmbedProvider[] = [
  {
    id: "loom",
    name: "Loom",
    regex: /^https?:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-zA-Z]+)\/?/,
    getEmbedUrl: (match, url) => {
      if (url.includes("/embed/")) {
        return url;
      }
      return `https://loom.com/embed/${match[1]}`;
    },
  },
  {
    id: "airtable",
    name: "Airtable",
    regex: /^https:\/\/(www.)?airtable.com\/([a-zA-Z0-9]{2,})\/.*/,
    getEmbedUrl: (match, url: string) => {
      const path = url.split("airtable.com/");
      if (url.includes("/embed/")) {
        return url;
      }
      return `https://airtable.com/embed/${path[1]}`;
    },
  },
  {
    id: "figma",
    name: "Figma",
    regex:
      /^https:\/\/[\w\.-]+\.?figma.com\/(file|proto|board|design|slides|deck)\/([0-9a-zA-Z]{22,128})/,
    getEmbedUrl: (match, url: string) => {
      return `https://www.figma.com/embed?url=${url}&embed_host=docmost`;
    },
  },
  {
    id: "typeform",
    name: "Typeform",
    regex: /^(https?:)?(\/\/)?[\w\.]+\.typeform\.com\/to\/.+/,
    getEmbedUrl: (match, url: string) => {
      return url;
    },
  },
  {
    id: "miro",
    name: "Miro",
    regex: /^https:\/\/(www\.)?miro\.com\/app\/board\/([\w-]+=)/,
    getEmbedUrl: (match, url) => {
      if (url.includes("/live-embed/")) {
        return url;
      }
      return `https://miro.com/app/live-embed/${match[2]}?embedMode=view_only_without_ui&autoplay=true&embedSource=docmost`;
    },
  },
  {
    id: "youtube",
    name: "YouTube",
    regex:
      /^(?:(?:https?:)?\/\/)?(?:(?:www|m|music)\.)?(?:youtube(?:-nocookie)?\.com\/(embed)\/|(?:youtube\.com|youtu\.be)\/(?:[\w-]+\?v=|v\/)?)([\w-]+)\S*$/i,
    getEmbedUrl: ([, playerPath, videoId], url) =>
      playerPath ? url : `https://www.youtube-nocookie.com/embed/${videoId}`,
    getLinkUrl: getYoutubeLinkUrl,
  },
  {
    id: "vimeo",
    name: "Vimeo",
    regex:
      /^(https:)?\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)(?:\/([\da-zA-Z]+))?/,
    getEmbedUrl: (match, url: string) => {
      // preserve ?h= hash for unlisted videos
      const hash =
        match[5] ?? new URL(url, "https://vimeo.com").searchParams.get("h");
      const base = `https://player.vimeo.com/video/${match[4]}`;
      return hash ? `${base}?h=${hash}` : base;
    },
  },
  {
    id: "framer",
    name: "Framer",
    regex: /^https:\/\/(www\.)?framer\.com\/embed\/([\w-]+)/,
    getEmbedUrl: (match, url: string) => {
      return url;
    },
  },
  { id: "gdrive", name: "Google Drive", ...googleDrive },
  // Embeds saved with the old Google Sheets option still use this id.
  { id: "gsheets", name: "Google Sheets", ...googleDrive },
  {
    id: "iframe",
    name: "Iframe",
    regex: /any-iframe/,
    getEmbedUrl: (match, url) => {
      return url;
    },
  },
];

export function getEmbedProviderById(id: string) {
  return embedProviders.find(
    (provider) => provider.id.toLowerCase() === id.toLowerCase(),
  );
}

export interface IEmbedResult {
  embedUrl: string;
  linkUrl: string;
  provider: string;
  providerId: string;
  label: string;
}

export function getEmbedUrlAndProvider(url: string): IEmbedResult {
  for (const provider of embedProviders) {
    const match = url.match(provider.regex);
    if (match) {
      return {
        embedUrl: provider.getEmbedUrl(match, url),
        linkUrl: provider.getLinkUrl?.(match, url) ?? url,
        provider: provider.name.toLowerCase(),
        providerId: provider.id,
        label: provider.getLabel?.(match) ?? provider.name,
      };
    }
  }
  return {
    embedUrl: url,
    linkUrl: url,
    provider: "iframe",
    providerId: "iframe",
    label: getIframeLabel(url),
  };
}

function getIframeLabel(url: string): string {
  try {
    return new URL(url).hostname.replace(/^www\./, "") || "Iframe";
  } catch {
    return "Iframe";
  }
}
