import * as React from "react";
import { useGetKey, useGetSet } from "../../hooks";
import { useDebugEvents } from "../../utils";
import { composeEventHandlers } from "../../utils/composeEvents";
import type { SrcContext } from "../Image";

export type VideoProps = React.ComponentPropsWithoutRef<"video"> & {
  "data-id": string;
  poster: string | SrcContext;
  src: string | SrcContext;
  crossOrigin?: boolean;
};

export const Video = React.forwardRef(function Video(
  { poster, onPlay, onPause, onEnded, src, crossOrigin, ...rest }: VideoProps,
  ref: React.ForwardedRef<HTMLVideoElement>,
) {
  const key = useGetKey(rest);
  const [_, setState] = useGetSet(key, { isPlaying: false });
  const { ...props } = useDebugEvents<VideoProps>(
    Object.assign(rest as VideoProps, {
      onPlay: composeEventHandlers(() => {
        setState(
          { isPlaying: true },
          process.env.PREVIEW ? `onPlay` : undefined,
        );
      }, onPlay),
      onPause: composeEventHandlers(() => {
        setState(
          { isPlaying: false },
          process.env.PREVIEW ? `onPause` : undefined,
        );
      }, onPause),
      onEnded: composeEventHandlers(() => {
        setState(
          { isPlaying: false },
          process.env.PREVIEW ? `onEnded` : undefined,
        );
      }, onEnded),
    }),
  );

  return (
    <video
      ref={ref}
      data-component="Video$Brevity"
      {...props}
      crossOrigin={crossOrigin ? "anonymous" : undefined}
      src={(src as SrcContext)?.src ?? src}
      poster={(poster as SrcContext)?.src ?? poster}
      data-id={key}
    />
  );
});
