import type { ReactElement } from 'react';
import React from 'react';
import type { StyleProp, ViewStyle } from 'react-native';
import Icon from '../Icon';
import {
  IconButtonLabel,
  IconButtonWrapper,
  ToolbarItemWrapper,
  StyledLabel,
} from './StyledToolbar';
import type { IconName } from '../Icon';

export interface ToolbarItemProps {
  /**
   * Visual intent of the toolbar item.
   */
  intent?: 'primary' | 'secondary' | 'info' | 'success' | 'danger' | 'warning';
  /**
   * Icon of the toolbar item.
   */
  icon?: IconName;
  /**
   * Action label of the toolbar item.
   */
  label?: string;
  /**
   * Callback that trigger when user press the toolbar item.
   */
  onPress?: () => void;
  /**
   * Whether the toolbar item is disabled.
   */
  disabled?: boolean;

  /**
   * Addtitional style.
   */
  style?: StyleProp<ViewStyle>;
}

type IconItemProps = {
  icon: IconName;
  label?: string;
  intent?: ToolbarItemProps['intent'];
  disabled?: boolean;
};

const IconItem = ({ icon, intent, disabled, label }: IconItemProps) => {
  return (
    <IconButtonWrapper>
      <Icon
        icon={icon}
        size="medium"
        intent={disabled ? 'disabled-text' : intent}
        testID={`toolbar-item-icon-${icon}`}
      />
      {label ? (
        <IconButtonLabel
          variant="regular-bold"
          intent={disabled ? 'subdued' : intent}
          allowFontScaling={false}
          numberOfLines={1}
        >
          {label}
        </IconButtonLabel>
      ) : null}
    </IconButtonWrapper>
  );
};

type ToolbarItemContentProps = {
  icon?: IconName;
  label?: string;
  intent?: ToolbarItemProps['intent'];
  disabled?: boolean;
};
const ToolbarItemContent = ({
  icon,
  label,
  intent = 'primary',
  disabled = false,
}: ToolbarItemContentProps): ReactElement | null => {
  if (icon) {
    return (
      <IconItem icon={icon} intent={intent} disabled={disabled} label={label} />
    );
  }
  if (label) {
    return (
      <StyledLabel
        variant="regular-bold"
        intent={disabled ? 'disabled' : intent}
        allowFontScaling={false}
        numberOfLines={1}
      >
        {label}
      </StyledLabel>
    );
  }
  return null;
};
const ToolbarItem = ({
  icon,
  label,
  onPress,
  intent = 'primary',
  disabled = false,
  style,
}: ToolbarItemProps) => {
  return (
    <ToolbarItemWrapper onPress={onPress} disabled={disabled} style={style}>
      <ToolbarItemContent
        icon={icon}
        label={label}
        intent={intent}
        disabled={disabled}
      />
    </ToolbarItemWrapper>
  );
};

export default ToolbarItem;
