import React from "react";
import devIcons from "../index";
import type { IconKey } from "../types";

export interface DevIconProps
  extends Omit<React.SVGAttributes<SVGElement>, "name"> {
  /** The name of the icon to display */
  name: IconKey;
  /** Optional size in pixels (both width and height) */
  size?: number;
  /** Optional className for additional styling */
  className?: string;
}

export const DevIcon: React.FC<DevIconProps> = ({
  name,
  size = 24,
  className = "",
  ...props
}) => {
  const icon = devIcons.getIcon(name as string);

  if (!icon) {
    console.warn(`Icon "${name}" not found`);
    return null;
  }

  // Parse the SVG string to get its attributes
  const parser = new DOMParser();
  const doc = parser.parseFromString(icon.icon, "image/svg+xml");
  const svg = doc.querySelector("svg");

  if (!svg) {
    console.warn(`Invalid SVG content for icon "${name}"`);
    return null;
  }

  // Create props object with merged attributes
  const svgProps = {
    ...props,
    width: size,
    height: size,
    className: `dev-icon ${className}`.trim(),
    dangerouslySetInnerHTML: { __html: svg.innerHTML },
  };

  // Return the SVG element with the merged props
  return React.createElement("svg", svgProps);
};

export default DevIcon;
