import * as React from "react";
import { useConfiguration } from "../../reactHooks/useConfiguration";
import { useEffect } from "react";
import { playerManager } from "./index";
import { useValidatePlayerConfig } from "../../playerUtils/useValidatePlayerConfig";
import { PlayerRole } from "./conts";
import { isAppleTV } from "@applicaster/zapp-react-native-ui-components/Helpers/Platform";

// TODO: Rename to ControllerType
export const usePlayerControllerSetup = ({
  props,
  ControllerType,
  ref,
  manifest,
  pluginId,
}: {
  props;
  ControllerType;
  ref;
  manifest;
  pluginId;
}) => {
  const [playerController, setPlayerController] = React.useState(null);
  const playerId = props?.playerId;
  const entry = props?.entry;

  const config = useConfiguration({
    entry,
    pluginIdentifier: pluginId,
    pluginManifest: manifest,
    component: null,
    skipDefaults: false,
  });

  useValidatePlayerConfig(config);

  useEffect(() => {
    const newConfig = isAppleTV()
      ? { supports_native_controls: true, ...config }
      : config;

    const newPlayerController = new ControllerType({
      player: ref,
      listener: props as any,
      config: newConfig,
      playerId,
      entry,
      playerPluginId: pluginId,
      playerRole: PlayerRole.Primary,
    });

    setPlayerController(newPlayerController);
  }, [playerId, entry?.id]);

  React.useEffect(() => {
    if (!playerController) {
      return;
    }

    if (!playerManager) {
      return;
    }

    if (playerManager.isPlayerRegistered(playerId)) {
      return;
    }

    playerManager.registerPlayer({
      id: playerId,
      playerController,
    });

    return () => {
      playerManager.unregisterPlayer(playerId);
      playerController.destroy?.();
    };
  }, [playerId, playerController]);

  return playerController;
};
