import { createRoot } from "react-dom/client";
import { Menu } from "./menu";
import { useEffect, useState } from "react";
import { MediaContainer } from "./media";
import { MinistreamApiClient, StreamInfo } from "./api";
import React from "react";
import * as Log from "./log";

interface AppProps {
  api: MinistreamApiClient;
}

const titleKey = "ministream.title";

function setTitleFromLocalstorage() {
  const title = localStorage.getItem(titleKey);
  if (title) {
    setTitle(title);
  }
}

function setTitle(title: string) {
  const el = document.querySelector("title");
  if (el) {
    el.textContent = title;
  }
}

export function App({ api }: AppProps) {
  const [streamList, setStreamList] = useState<StreamInfo[]>([]);
  const [selectedStream, setSelectedStream] = useState<string | null>(null);

  const updateSelect = (item: string | null) => {
    setSelectedStream(item);
  };

  const updateTitle = () => {
    api.siteInfo().then((info) => {
      if (info.siteName != document.title) {
        setTitle(info.siteName);
        localStorage.setItem(titleKey, info.siteName);
      }
    });
    return;
  };

  useEffect(() => {
    const updateStreamList = () => {
      api.listStreams().then((list) => {
        setStreamList((current) => {
          if (list.length != current.length) {
            Log.Debug("Updated streamList!");
            return list;
          }
          if (
            !list.every((_, idx) => {
              return list[idx].streamKey === current[idx].streamKey;
            })
          ) {
            Log.Debug("Updated streamList..");
            return list;
          }
          return current;
        });
      });
    };

    updateStreamList();
    const updateInterval = setInterval(() => {
      updateStreamList();
    }, 10000);
    return () => clearInterval(updateInterval);
  }, []);

  useEffect(() => {
    updateTitle();
  }, []);

  return (
    <>
      <Menu
        items={streamList}
        selectedItem={selectedStream}
        selectCallback={updateSelect}
      />
      <MediaContainer selectedStream={selectedStream} api={api} />
    </>
  );
}

const rootElement = document.getElementById("app");
setTitleFromLocalstorage();
if (rootElement) {
  const root = createRoot(rootElement);
  const api = new MinistreamApiClient();
  root.render(<App api={api} />);
}
