import React, { useEffect, useState } from "react";
import classNames from "classnames";

import ReactPlayer from "react-player";
import { ReactPlayerProps } from "react-player/types";

import { filterAttrs } from "@arc-ui/community-utils/filter-attrs";

import { VideoCardPlayIcon } from "./components/VideoCardPlayIcon";
import { PlayerProps } from "./types/player-props";

import styles from "./VideoCardPlayer.module.css";

export const VideoCardPlayer = ({
  thumbnail,
  playIconSize,
  orientation,
  children,
  player,
  ...props
}: VideoCardPlayerProps) => {
  const [isClient, setIsClient] = useState<boolean>(false);

  useEffect(() => {
    setIsClient(true);
  }, []);

  const playerProps = {
    ...player,
    light: thumbnail,
    playIcon: <VideoCardPlayIcon size={playIconSize} />,
    muted: !thumbnail,
    playing: true,
    controls: true,
    className: styles.player,
    width: "100%",
    height: "100%",
  };

  return (
    <div className={styles.container} {...filterAttrs(props)}>
      <div
        data-testid="arc-video-card"
        className={classNames(
          styles.playerWrapper,
          styles[`playerWrapper--${orientation}`],
        )}
      >
        {isClient && <ReactPlayer {...playerProps} />}
      </div>
      {children}
    </div>
  );
};

export interface VideoCardPlayerProps {
  player: PlayerProps;
  orientation: "portrait" | "landscape";
  playIconSize: "s" | "l";
  thumbnail?: ReactPlayerProps["light"];
  children?: React.ReactNode;
}
