import jsonp from "fetch-jsonp";
import React, { useState, useEffect } from "react";
import { Platform } from "react-native";

import Embed from "./Embed";

type Endpoints = {
  [platform: string]: {
    url: string;
    jsonp?: boolean;
  };
};

const endpoints: Endpoints = {
  twitter: {
    url: "https://publish.twitter.com/oembed",
    jsonp: true,
  },
  instagram: {
    url: "https://api.instagram.com/oembed/",
  },
  facebook: {
    url: "https://m.facebook.com/plugins/post/oembed.json/",
    jsonp: true,
  },
};

export type SocialPlatform = keyof typeof endpoints;

type Props = {
  url: string;
  platform: SocialPlatform;
  maxWidth?: number;
};

// Facebook enforces a min width of 350
// Greater than instagram (326) and Twitter (220)
const Social = ({ url, platform, maxWidth = 350 }: Props) => {
  const [errorMessage, setErrorMessage] = useState("");
  const [oembed, setOEmbed] = useState(null);

  useEffect(() => {
    setErrorMessage("");
    (async () => {
      try {
        const get =
          Platform.OS === "web" && endpoints[platform].jsonp ? jsonp : fetch;
        const res = await get(
          `${endpoints[platform].url}?url=${url}&maxwidth=${maxWidth}`
        );
        const oembedJson = await res.json();
        setOEmbed(oembedJson);
      } catch (err) {
        setErrorMessage(
          err?.message ||
            `There was a problem loading this content from ${platform}.`
        );
      }
    })();
  }, [url]);

  return (
    <Embed
      html={oembed?.html}
      errorMessage={errorMessage}
      initialWidth={maxWidth}
    />
  );
};

export default Social;
