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";
import { TVSeekController } from "../../reactHooks/player/TVSeekControlller/TVSeekController";
import { KeyInputHandler } from "../keyInputHandler/KeyInputHandler";
import { isTV } from "../../reactUtils";

// 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 combinedProps = {
      player: ref,
      listener: props as any,
      config: newConfig,
      playerId,
      entry,
      playerPluginId: pluginId,
      playerRole: PlayerRole.Primary,
    };

    setPlayerController(new ControllerType(combinedProps));
  }, [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]);

  useEffect(() => {
    if (!isTV()) {
      return;
    }

    if (playerController) {
      const seekController = new TVSeekController(playerController);
      playerController.seekController = seekController;

      return KeyInputHandler.getInstance().addListener(seekController);
    }
  }, [playerController]);

  return playerController;
};
