import { type Dispatch, forwardRef, type SetStateAction } from 'react';

import { IconPlayerPlay } from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import { type SxProps } from '@material-hu/mui/styles';

import HuAvatar, {
  type AvatarProps,
} from '@material-hu/components/design-system/Avatar';

import { type AttachmentLoadError } from 'src/pages/dashboard/Conversations/types';

import LazySecureVideo from './LazySecureVideo';

export type LazySecureAwareVideoProps = {
  isSecure?: boolean;
  conversationId?: string;
  url: string;
  thumbUrl?: string;
  sxSecure: SxProps;
  sxDefault: SxProps;
  hasControls?: boolean;
  onLoadedMetadata?: (e?: React.SyntheticEvent<HTMLVideoElement>) => void;
  hasPlayerButton?: boolean;
  onCanPlay?: () => void;
  onLoadStart?: () => void;
  avatarSize?: AvatarProps['size'];
  canSeeVideo?: boolean;
  onUpdateAttachmentLoadError?: Dispatch<SetStateAction<AttachmentLoadError>>;
};

const LazySecureAwareVideo = forwardRef<
  HTMLVideoElement,
  LazySecureAwareVideoProps
>((props, ref) => {
  const {
    isSecure,
    url,
    sxSecure,
    sxDefault,
    hasControls = false,
    thumbUrl = '',
    onLoadedMetadata,
    hasPlayerButton = true,
    onCanPlay,
    onLoadStart,
    avatarSize,
    canSeeVideo = false,
    onUpdateAttachmentLoadError,
    conversationId,
  } = props;

  if (!isSecure) {
    return (
      <LazySecureVideo
        conversationId={conversationId}
        ref={ref}
        sx={sxSecure}
        url={url}
        avatarSize={avatarSize}
        hasPlayerButton={hasPlayerButton}
        hasControls={hasControls}
        thumbnailUrl={thumbUrl}
        onLoadedMetadata={onLoadedMetadata}
        onCanPlay={onCanPlay}
        onLoadStart={onLoadStart}
        canSeeVideo={canSeeVideo}
        onUpdateAttachmentLoadError={onUpdateAttachmentLoadError}
      />
    );
  }

  return (
    <Box sx={{ ...sxDefault, position: 'relative' }}>
      {hasPlayerButton && (
        <Box
          sx={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            zIndex: 1,
          }}
        >
          <HuAvatar
            Icon={IconPlayerPlay}
            size={avatarSize}
          />
        </Box>
      )}
      <video
        ref={ref}
        src={url}
        onLoadedMetadata={onLoadedMetadata}
        preload="metadata"
        controls={hasControls}
        poster={thumbUrl}
        style={{ width: '100%' }}
      />
    </Box>
  );
});

LazySecureAwareVideo.displayName = 'LazySecureAwareVideo';

export default LazySecureAwareVideo;
