import type { FC } from 'react';
import React, { useState } from 'react';
import cx from 'classnames';
import { useImage } from './useImage';

const CLASS_NAME = 'Image';

export interface ImageProps {
    alt?: string;
    className?: string;
    testId?: string;
    /**
     * Element to render while loading or if an error occurs
     */
    placeholder: JSX.Element;

    /**
     * Image source url or list of urls (until one loads)
     */
    src: string | string[];
    useSuspense?: boolean;
}

/**
 * Please use CoverArt or UserThumb instead. If you need a different kind of image in your app, please get in touch with the OSP team.
 *
 * @deprecated Please use CoverArt or UserThumb instead.
 * @type atom
 * @status deprecated
 * @tags visuals
 */
export const Image: FC<ImageProps> = ({
    alt,
    className,
    testId = CLASS_NAME,
    placeholder,
    src: srcList,
    useSuspense = false,
}) => {
    const [hasError, setHasError] = useState(false);
    const { src, isLoading, error } = useImage({
        srcList,
        useSuspense,
    });

    if (isLoading || hasError || error) {
        return placeholder;
    }

    return (
        <img
            src={src}
            {...(alt && { alt })}
            data-testid={testId}
            className={cx(className, CLASS_NAME)}
            referrerPolicy="no-referrer"
            onError={() => setHasError(true)}
        />
    );
};
