import React from 'react';

import * as Icons from '@/icons';

// Filter out non-component exports and create the icon map
const ICON_MAP = Object.entries(Icons).reduce(
  (acc, [key, value]) => {
    // Check if the value is a React component (function that takes props)
    if (typeof value === 'function') {
      acc[key] = value as React.FC<React.SVGProps<SVGSVGElement>>;
    }
    return acc;
  },
  {} as Record<string, React.FC<React.SVGProps<SVGSVGElement>>>
);

export type IconName = keyof typeof ICON_MAP;

/**
 * Get an icon component by name
 * @param iconName - The name of the icon component
 * @returns The icon component or null if not found
 */
export function getIconComponent(
  iconName: string
): React.FC<React.SVGProps<SVGSVGElement>> | null {
  return ICON_MAP[iconName] || null;
}

/**
 * Render an icon by name with the given props
 * @param iconName - The name of the icon to render
 * @param props - Props to pass to the icon component
 * @returns The rendered icon JSX element or null if icon not found
 */
export function renderIcon(
  iconName: string | null | undefined,
  props: React.SVGProps<SVGSVGElement> = {}
): React.ReactElement | null {
  if (!iconName) return null;

  const IconComponent = getIconComponent(iconName);
  if (!IconComponent) {
    console.warn(`Icon "${iconName}" not found in icon map`);
    return null;
  }

  return <IconComponent {...props} />;
}

/**
 * Check if an icon name exists in the icon map
 * @param iconName - The name to check
 * @returns True if the icon exists, false otherwise
 */
export function isValidIconName(iconName: string): iconName is IconName {
  return iconName in ICON_MAP;
}

/**
 * Get all available icon names
 * @returns Array of all available icon names
 */
export function getAvailableIconNames(): IconName[] {
  return Object.keys(ICON_MAP) as IconName[];
}

// Export the icon map for direct access if needed
export { ICON_MAP };
