'use client'

import React, { Suspense, lazy, ComponentType } from 'react'
import { SmartIconType } from '@/types/iconType'

type IconsaxIconProps = {
  size?: number
  color?: string
  className?: string
  variant?: string
}

export interface SmartIconProps {
  icon?: SmartIconType
  name?: string
  size?: number
  color?: string
  className?: string
  variant?: string
}

export const SmartIcon: React.FC<SmartIconProps> = ({
  icon,
  name,
  size,
  color,
  className,
  variant
}) => {
  const iconName =
    (icon?.Name || name || '').charAt(0).toUpperCase() +
    (icon?.Name || name || '').slice(1)

  if (!iconName) return null

  // Lazy-load icon dynamically with proper type cast
  const IconComponent = lazy(() =>
    import('iconsax-react').then(module => {
      const Component = module[
        iconName as keyof typeof module
      ] as ComponentType<IconsaxIconProps>
      return { default: Component }
    })
  )

  return (
    <Suspense fallback={null}>
      <IconComponent
        variant={icon?.Variant ?? variant ?? 'linear'}
        size={icon?.Size ?? size ?? 20}
        color={icon?.Color ?? color ?? 'currentColor'}
        className={icon?.ClassName ?? className}
      />
    </Suspense>
  )
}
