import React, { useState, useEffect } from 'react';
import { Icon } from '@iconify/react';
import { motion } from 'framer-motion';
import { Box, Tooltip } from '@mui/material';

export default function Iconify({ icon, size = 22, style = {}, ...props }: { icon: string, size?: number, style?: React.CSSProperties }) {
  const [isLoaded, setIsLoaded] = useState(false);
  const [hasError, setHasError] = useState(false);

  useEffect(() => {
    setIsLoaded(false);
    setHasError(false);

    // Create an image element to preload the icon
    const image = new Image();
    image.src = `https://api.iconify.design/${icon}.svg`;

    // Handle successful loading
    image.onload = () => setIsLoaded(true);

    // Handle loading error
    image.onerror = (ev) => {
      console.log("ev", ev);
      setHasError(true);
      setIsLoaded(true);
    };
  }, [icon]);

  if (hasError) {
    // Optionally, return a fallback icon or placeholder
    return (
      <Box
        sx={{
          width: size,
          height: size,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: 'rgba(0, 0, 0, 0.1)',
          borderRadius: '50%',
        }}
      >
        <Tooltip title="This image could not be loaded.">
        <span role="img" aria-label="error" style={{ fontSize: size }}>
          ⚠️
        </span>
        </Tooltip>
      </Box>
    );
  }

  return (
    <motion.div
      animate={{ opacity: isLoaded ? 1 : 0 }}
      style={{ display: 'flex' }}
    >
      {isLoaded && <Icon style={style} icon={icon} width={size} height={size} {...props} />}
    </motion.div>
  );
}
