import React from 'react'

import iconsList from './iconsList'
import { type IconProps } from './Icon.models'
import { cn } from '../../services/cn'

const strokeBasedIcons = new Set([
  'barCodeNo',
  'buildingBox',
  'clockDollar',
  'databaseOff',
  'downCaret',
  'fileSearch',
  'fileTextSpark',
  'folderOff',
  'folderX',
  'infoDocument',
  'packageExport',
  'presentationOff',
  'receiptRefund',
  'receiptDollar',
  'reportSearch',
  'users',
  'heartExclamation',
  'dollarExclamation',
  'calendarClock',
  'curveDown',
  'curveUp',
  'forwardSlant',
  'trendingDown',
  'trendingUp',
  'confetti',
  'copy',
  'eyeClosed',
  'eyeOpen',
  'subtitlesAi',
  'aiEdit',
  'reOptimize',
])

const Icon = ({
  icon,
  className = '',
  iconSize = '20px',
  color = 'purple',
  qaTestId = 'icon',
  style,
}: IconProps): React.JSX.Element => {
  const width = style?.width ?? iconSize
  const height = style?.height ?? iconSize

  const sharedProps = {
    className: cn('icon flex items-center', className),
    'qa-test-id': qaTestId,
  }

  if (typeof icon === 'string') {
    const iconElement = React.cloneElement(iconsList[icon], {
      width,
      height,
      style,
    })

    return (
      <span
        {...sharedProps}
        className={cn(
          'icon flex items-center',
          icon,
          // Base SVG styles - apply color directly to all SVG elements (including nested)
          '[&_circle]:fill-[var(--svg-color)] [&_path]:fill-[var(--svg-color)] [&_rect]:fill-[var(--svg-color)]',
          // Stroke-based icons
          strokeBasedIcons.has(icon) &&
            '[&_path]:fill-none [&_path]:stroke-[var(--svg-color)]',
          // Star half solid special case
          icon === 'starHalfSolid' && '[&_path]:fill-[revert-layer]',
          sharedProps.className,
        )}
        style={
          {
            '--svg-color': `var(--${color})`,
          } as React.CSSProperties
        }
        data-testid={`icon-${icon}`}
      >
        {iconElement}
      </span>
    )
  } else {
    const IconElement = icon

    return (
      <span
        {...sharedProps}
        style={{
          color: `var(--${color})`,
        }}
        data-testid={`icon-${qaTestId}`}
      >
        <IconElement width={width} height={height} style={style} />
      </span>
    )
  }
}
export default Icon
