import {
  FunctionComponent,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from "react";
import styles from "./ScreenSharingPage.module.css";
import { Panel } from "../../components/Panel/Panel";
import { Link, useParams } from "react-router-dom";
import { ScreenViewer } from "./ScreenViewer";
import adapter from "webrtc-adapter";
import { Button } from "../../components/Button/Button";
import {
  ScreenSharingServer,
  ScreenSharingServerState,
  StateChangedEvent,
  StateChangedEventType,
} from "../../api/webrtc";

export const ScreenSharingPage: FunctionComponent = () => {
  const { sessionId } = useParams<{ sessionId: string }>();
  const [server, setServer] = useState<ScreenSharingServer | null>(null);
  const [state, setState] = useState<string | null>(null);

  const onServerStateChanged = useCallback((evt: Event) => {
    setState((evt as StateChangedEvent).state);
  }, []);

  console.log("Server state", state);

  const onShareScreenClick = useCallback(() => {
    const server = new ScreenSharingServer();
    server.addEventListener(StateChangedEventType, onServerStateChanged);
    server.shareScreen({
      video: true,
      audio: false,
    });
    setServer(server);
    return () => {
      server.removeEventListener(StateChangedEventType, onServerStateChanged);
      server.close();
      setServer(null);
    };
  }, [onServerStateChanged]);

  const onStopSharingClick = useCallback(() => {
    if (!server) return;
    server.close();
    setServer(null);
    setState(null);
  }, [server]);

  useEffect(() => {
    if (!server) return;
    return () => {
      if (!server) return;
      console.log("Closing screen sharing server");
      server.close();
      setServer(null);
    };
  }, [server]);

  if (sessionId !== undefined) {
    return <ScreenViewer sessionId={sessionId} />;
  }

  return (
    <div className={styles.root}>
      <Panel>
        <Link to="/">Back to homepage</Link>
        <h1 className={styles.panelTitle}>Screen sharing</h1>
        {state === ScreenSharingServerState.Sharing ? (
          <Button onClick={onStopSharingClick}>Stop sharing</Button>
        ) : (
          <Button onClick={onShareScreenClick}>Share screen</Button>
        )}
      </Panel>
    </div>
  );
};
