import { createRoot } from "react-dom/client";
import React from "react";
import { Menu } from "./menu";
import { createContext, useState } from "react";
import { MediaContainer } from "./media";
import { MinistreamApiClient } from "./api";

type ThemeContextType = "light" | "dark";

const ThemeContext = createContext<ThemeContextType>("light");

type AppState = {
    streamList: string[]
    selectedStream: string | undefined
}
type AppProps = {}

export class App extends React.Component<AppProps, AppState> {
    apiClient: MinistreamApiClient
    constructor(props: AppProps) {
        super(props)
        this.state = {
            streamList: [],
            selectedStream: undefined
        }
        this.apiClient = new MinistreamApiClient()
        this.updateSelect = this.updateSelect.bind(this)
    }

    async componentDidMount(): Promise<void> {
        const streams = await this.apiClient.listStreams()
        this.setState((state) => {
            return { selectedStream: state.selectedStream, streamList: streams }
        })
    }

    updateSelect(selected: string): void {
        this.setState((state) => {
            return { streamList: state.streamList, selectedStream: selected }
        })
    }

    render() {
        return (
            <>
                <Menu
                    items={this.state.streamList}
                    selectedItem={this.state.selectedStream}
                    selectCallback={this.updateSelect}
                />
                <MediaContainer selectedStream={this.state.selectedStream} api={this.apiClient} />
            </>
        )
    }
}

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