import React, { useEffect, useState } from "react";
import { AuthProvider, useAuth } from "components/Login/AuthContext";
import Login from "components/Login";
import Analytics from "components/Analytics";
import Editor from "components/Editor";
import { EditableLink } from "components/Editor/Link";

const EditorPage: React.FC = () => {
  const { loggedIn, headers } = useAuth();
  const [links, setLinks] = useState<EditableLink[]>([]);

  useEffect(() => {
    async function fetchLinks() {
      if (!loggedIn) return;

      const res = await fetch("/api/editor/links", { headers });
      const links = await res.json();
      setLinks(links);
    }

    fetchLinks();
  }, [loggedIn, headers]);

  return loggedIn ? (
    <>
      <Analytics clicks={links.reduce((acc, curr) => acc + curr.clicks, 0)} />
      <Editor links={links} setLinks={setLinks} />
    </>
  ) : (
    <Login />
  );
};

export default function EditorPageWrapper(): JSX.Element {
  return (
    <AuthProvider>
      <EditorPage />
    </AuthProvider>
  );
}
