import React, { ImgHTMLAttributes, forwardRef, useEffect, useState } from 'react';
import { useAuthenticatedMediaUrl } from '../../hooks/useAuthenticatedMediaUrl';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';

export interface AuthenticatedMediaProps
  extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> {
  /** The source URL of the media (may be an authenticated media URL) */
  src?: string;
  /** Override for authentication - if not provided, uses useMediaAuthentication hook */
  useAuthentication?: boolean;
}

/**
 * Image component that handles Matrix authenticated media.
 * Automatically fetches authenticated media URLs with the proper Authorization header
 * and renders them as blob URLs.
 */
export const AuthenticatedMedia = forwardRef<HTMLImageElement, AuthenticatedMediaProps>(
  ({ src, useAuthentication: useAuthOverride, ...props }, ref) => {
    const useAuthFromServer = useMediaAuthentication();
    const useAuthentication = useAuthOverride ?? useAuthFromServer;
    const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);

    return <img ref={ref} {...props} src={authenticatedSrc} />;
  }
);

AuthenticatedMedia.displayName = 'AuthenticatedMedia';

/**
 * A simpler authenticated img component for use in places like custom HTML parsers.
 * This component handles its own authentication state.
 */
export interface AuthenticatedImgProps extends ImgHTMLAttributes<HTMLImageElement> {}

export const AuthenticatedImg = forwardRef<HTMLImageElement, AuthenticatedImgProps>(
  ({ src, ...props }, ref) => {
    const useAuthentication = useMediaAuthentication();
    const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);

    return <img ref={ref} {...props} src={authenticatedSrc} />;
  }
);

AuthenticatedImg.displayName = 'AuthenticatedImg';
