import { useState } from 'react';
import { joinURL } from 'ufo';
import { SxProps } from '@mui/material';

import Img from '../Img';
import { isUrl } from '../Util';
import DidAvatar from '../Avatar';

type AppIconProps = {
  appInfo: any;
  size?: number;
  sx?: SxProps;
};

export default function AppIcon({ appInfo, size = 32, ...rest }: AppIconProps) {
  const [error, setError] = useState(false);
  if (error || !(appInfo.appUrl || appInfo.appLogo)) {
    return <DidAvatar did={appInfo.appPid} size={size} />;
  }

  let logoUrl = appInfo.appLogo || '';
  if (!isUrl(logoUrl)) {
    logoUrl = joinURL(appInfo.appUrl || '', logoUrl);
  }

  return (
    <Img
      src={logoUrl}
      alt={appInfo.appName || 'Blocklet Icon'}
      width={size}
      height={size}
      {...rest}
      onError={() => setError(true)}
    />
  );
}
