import type { FC } from 'react';
import React from 'react';
import { useAppConfig } from '@theorchard/suite-config';
import cx from 'classnames';

const CLASS_NAME = 'CdnIcon';

export interface CdnIconProps {
    /**
     * The file path including extension.
     * @example "/logos/my-image.svg"
     */
    filePath: string;
    folder?: string;
    alt?: string;
    className?: string;
    testId?: string;
    width?: string | number;
    height?: string | number;
    cdnUrl?: string;
    title?: string;
}

export const CdnIcon: FC<CdnIconProps> = ({
    filePath,
    folder = 'icons',
    alt,
    className,
    testId = CLASS_NAME,
    width,
    height,
    cdnUrl,
    title,
}) => {
    const config = useAppConfig();
    const cdn = cdnUrl ?? config?.cdnUrl ?? '/';

    const imgSrcBase = !cdn.endsWith('/') ? cdn : cdn.substring(0, cdn.length - 1);

    const trimmedFilePath = !filePath.startsWith('/') ? filePath : filePath.substring(1);

    return (
        <img
            data-testid={testId}
            className={cx('Icon', CLASS_NAME, className)}
            alt={alt ?? filePath}
            width={width}
            height={height}
            title={title}
            src={`${imgSrcBase}/assets/${folder}/${trimmedFilePath}`}
        />
    );
};
