import styles from './index.module.scss';
import Icon from '../Icon/index.js';
import ContentFields from './ContentFields.js';
import StyleFields from './StyleFields.js';
import cx from '../utils/classname.js';
import {
  ButtonProps,
  ButtonAsButtonProps,
  ButtonAsLinkProps,
  BaseButtonProps,
  RenderWithIconProps,
} from './types.js';

const ButtonComponent = ({
  buttonType = 'link',
  variant = 'primaryButton',
  className = '',
  style = {},
  ...rest
}: ButtonProps) => {
  const defaultClasses = cx(styles.button, className);
  const sharedProps = {
    className: defaultClasses,
    style: style,
    'data-button-variant': variant,
  };

  const RenderWithIcon = ({
    iconFieldPath,
    iconSize,
    showIcon,
    iconPurpose,
    iconTitle,
    iconPosition = 'right',
    children,
  }: RenderWithIconProps) => {
    if (!iconFieldPath) return <>{children}</>;

    const icon = (
      <Icon
        fieldPath={iconFieldPath}
        size={iconSize}
        className={styles.icon}
        showIcon={showIcon}
        purpose={iconPurpose}
        title={iconTitle}
      />
    );

    return (
      <>
        {iconPosition === 'left' && icon}
        {children}
        {iconPosition === 'right' && icon}
      </>
    );
  };

  const renderButton = ({
    onClick,
    disabled = false,
    children,
    iconPosition = 'right',
    iconFieldPath,
    iconSize = 18,
    showIcon,
    iconPurpose,
    iconTitle,
    ...rest
  }: Omit<ButtonAsButtonProps, 'buttonType'> & Partial<BaseButtonProps>) => {
    const iconProps = {
      iconFieldPath,
      iconSize,
      showIcon,
      iconPurpose,
      iconTitle,
      iconPosition,
    };
    return (
      <button {...sharedProps} onClick={onClick} disabled={disabled} {...rest}>
        <RenderWithIcon {...iconProps}>{children}</RenderWithIcon>
      </button>
    );
  };

  const renderLink = ({
    href = '',
    target = '_self',
    rel = '',
    children,
    iconPosition = 'right',
    iconFieldPath,
    iconSize = 18,
    showIcon,
    iconPurpose,
    iconTitle,
    ...rest
  }: Omit<ButtonAsLinkProps, 'buttonType'> & Partial<BaseButtonProps>) => {
    const iconProps = {
      iconFieldPath,
      iconSize,
      showIcon,
      iconPurpose,
      iconTitle,
      iconPosition,
    };
    return (
      <a {...sharedProps} href={href} target={target} rel={rel} {...rest}>
        <RenderWithIcon {...iconProps}>{children}</RenderWithIcon>
      </a>
    );
  };

  // TypeScript properly discriminates based on buttonType
  if (buttonType === 'button') return renderButton(rest);

  // For link variant
  return renderLink(rest);
};

// Create compound component with proper typing
type ButtonComponentType = typeof ButtonComponent & {
  ContentFields: typeof ContentFields;
  StyleFields: typeof StyleFields;
};

const Button = ButtonComponent as ButtonComponentType;
Button.ContentFields = ContentFields;
Button.StyleFields = StyleFields;

export default Button;
