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

import { getDomainURL } from '@/config';
import { useAppConfig } from '@/contexts/AppConfigContext';
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 = getDomainURL();

    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;
