import { forwardRef, useEffect } from 'react';
import { View, type PressableProps } from 'react-native';
import {
  ButtonRoot,
  dataAttributes,
  mergeDataAttributes,
  type IButtonProps,
} from '@cdx-ui/primitives';
import type { ForgeIcon } from '@cdx-ui/icons';
import { cn } from '@cdx-ui/utils';
import { Icon, type IconProps } from '../Icon';
import {
  type IconButtonVariantProps,
  iconButtonGlyphVariants,
  iconButtonIconColorVariants,
  iconButtonRootVariants,
} from './styles';

export type IconButtonVariant = 'solid' | 'subtle' | 'ghost';

/** @deprecated Use {@link IconButtonVariant} (`'subtle'`) instead. */
export type IconButtonVariantTint = 'tint';

let hasWarnedIconButtonTintVariant = false;

export interface IconButtonProps
  extends PressableProps, IButtonProps, Omit<IconButtonVariantProps, 'variant'> {
  /**
   * Visual style variant.
   * @default 'solid'
   */
  variant?:
    | IconButtonVariant
    /** @deprecated Use `'subtle'` instead. */
    | 'tint';
  className?: string;
  /** Forge icon component to render (icon-only control). */
  as: ForgeIcon;
  /** Passed through to the underlying `Icon`. */
  iconClassName?: IconProps['className'];
}

const IconButtonRoot = forwardRef<View, IconButtonProps>(
  (
    {
      variant: variantProp = 'solid',
      color = 'neutral',
      size = 'default',
      className,
      style,
      as: IconComponent,
      iconClassName,
      accessibilityRole = 'button',
      ...props
    },
    ref,
  ) => {
    useEffect(() => {
      if (__DEV__ && variantProp === 'tint' && !hasWarnedIconButtonTintVariant) {
        hasWarnedIconButtonTintVariant = true;
        console.warn(
          '[IconButton] The `tint` variant is deprecated and will be removed in a future major release. Use `subtle` instead.',
        );
      }
    }, [variantProp]);

    const variant = variantProp === 'tint' ? 'subtle' : variantProp;

    const rootClassName = cn(iconButtonRootVariants({ variant, color, size }), className);

    const glyphClassName = cn(
      iconButtonGlyphVariants({ size }),
      iconButtonIconColorVariants({ variant, color }),
      iconClassName,
    );

    return (
      <ButtonRoot
        ref={ref}
        accessibilityRole={accessibilityRole}
        className={rootClassName}
        style={style}
        {...props}
        {...mergeDataAttributes(props, dataAttributes({ slot: 'icon-button' }))}
      >
        <Icon as={IconComponent} className={glyphClassName} />
      </ButtonRoot>
    );
  },
);

IconButtonRoot.displayName = 'IconButton';

export const IconButton = IconButtonRoot;

export type { IconButtonVariantProps };
