import {
  useEffect,
  useState,
} from 'react';

import { rpcClient } from '@/api/request';
import { useAppConfig } from '@/stores/appConfig';
import SVGCacheService from '@/utils/SVGCacheService';

type Props = {
  "icon"?: string
  size?: number
  color?: string
  style?: any;
  className?: string;
};


const removeHash = (str?: string) => {
  if (!str) {
    return "";
  }
  if (str.startsWith("#")) {
    return str.substring(1);
  }
  return str;
}

const SvgIcon = (props: Props) => {

  const size = props.size ?? 20;

  const { isDarkTheme } = useAppConfig();


  const [svg, setSvg] = useState<string>("");
  useEffect(() => {

    const color = props.color ? props.color : isDarkTheme ? '#E0E0E0' : '#37474F';


    const domainURL = rpcClient.getCurrentEndpointDomain();

    const url = `${domainURL}/_assets/icons/${!!props.icon ? props.icon : "border-all-variant"}?height=${size}&width=${size}&fill=${removeHash(color)}`;

    if (localStorage.getItem(url)) {
      setSvg(localStorage.getItem(url) ?? "");
      return;
    }

    SVGCacheService.getSvg(url).then((content) => {
      if (content) {
        setSvg(content);

        localStorage.setItem(url, content);

      }
    }
    );

  }, [props.icon, props.size, props.color, isDarkTheme]);


  return <span role="img" style={props.style}
    dangerouslySetInnerHTML={{ __html: svg ?? "" }}
    className={`anticon ant-menu-item-icon ${props.className}`}>
  </span>;

};

export default SvgIcon;
