import React from 'react';
import type { StyleProp, ViewStyle } from 'react-native';
import Icon from '../Icon';
import Typography from '../Typography';
import { useTheme } from '../../theme';
import AnimatedGradientText from './AnimatedGradientText';
import {
  getIconName,
  getIconIntent,
  getIconSize,
  getTextSizeName,
} from './utils';
import { StyledContainer, StyledIconContainer } from './StyledInlineLoader';
import type {
  InlineLoaderState,
  InlineLoaderIntent,
  InlineLoaderTextSize,
} from './types';

export interface InlineLoaderProps {
  /**
   * Text content displayed next to the icon.
   */
  text: string;
  /**
   * Current state of the loader.
   */
  state?: InlineLoaderState;
  /**
   * Visual intent.
   */
  intent?: InlineLoaderIntent;
  /**
   * Font size (px) — also controls icon size.
   */
  size?: InlineLoaderTextSize;
  /**
   * Additional container style.
   */
  style?: StyleProp<ViewStyle>;
  /**
   * Testing id.
   */
  testID?: string;
}

const InlineLoader = ({
  text,
  state = 'idle',
  intent = 'neutral',
  size = 14,
  style,
  testID,
}: InlineLoaderProps) => {
  const theme = useTheme();
  const textSizeName = getTextSizeName(size);
  const lineHeight = theme.__hd__.inlineLoader.icon.lineHeights[textSizeName];

  const iconName = getIconName(state);
  const iconIntent = getIconIntent(state, intent);
  const { size: iconSize, styleFontSize } = getIconSize(size);

  const iconStyle = styleFontSize ? { fontSize: styleFontSize } : undefined;
  const isAiLoading = state === 'loading' && intent === 'ai';

  return (
    <StyledContainer testID={testID} style={style}>
      <StyledIconContainer themeSize={textSizeName}>
        <Icon
          icon={iconName}
          intent={iconIntent}
          size={iconSize}
          spin={state === 'loading'}
          style={iconStyle}
          accessible={false}
          accessibilityElementsHidden
          importantForAccessibility="no-hide-descendants"
        />
      </StyledIconContainer>
      {isAiLoading ? (
        <AnimatedGradientText fontSize={size} lineHeight={lineHeight}>
          {text}
        </AnimatedGradientText>
      ) : (
        <Typography.Body intent="body" style={{ fontSize: size, lineHeight }}>
          {text}
        </Typography.Body>
      )}
    </StyledContainer>
  );
};

export default InlineLoader;
