import React, { ButtonHTMLAttributes, ReactNode } from 'react';
import styled, { css } from 'styled-components';

export interface IconButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  size?: 'sm' | 'md' | 'lg';
  tone?: 'neutral' | 'primary' | 'danger';
  label: string;
  children: ReactNode;
}

type StyledProps = {
  $size: NonNullable<IconButtonProps['size']>;
  $tone: NonNullable<IconButtonProps['tone']>;
};

const StyledIconButton = styled.button<StyledProps>`
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  border: none;
  border-radius: ${({ theme }) => theme.borderRadius.md};
  cursor: pointer;
  transition:
    background-color ${({ theme }) => theme.transitions.fast},
    color ${({ theme }) => theme.transitions.fast},
    box-shadow ${({ theme }) => theme.transitions.fast};
  color: ${({ theme }) => theme.colors.text.secondary};
  background: transparent;

  svg {
    width: ${({ $size }) => ($size === 'sm' ? 18 : $size === 'lg' ? 22 : 20)}px;
    height: ${({ $size }) => ($size === 'sm' ? 18 : $size === 'lg' ? 22 : 20)}px;
  }

  ${({ $size }) => {
    const dimension =
      $size === 'sm' ? '34px' : $size === 'lg' ? '44px' : '40px';
    return css`
      width: ${dimension};
      height: ${dimension};
    `;
  }}

  &:hover:not(:disabled) {
    background-color: ${({ theme }) => theme.colors.surfaceMuted};
    color: ${({ theme }) => theme.colors.text.primary};
  }

  ${({ $tone, theme }) =>
    $tone === 'danger' &&
    css`
      color: ${theme.colors.text.tertiary};
      &:hover:not(:disabled) {
        background-color: ${theme.colors.errorLight};
        color: ${theme.colors.error};
      }
    `}

  ${({ $tone, theme }) =>
    $tone === 'primary' &&
    css`
      color: ${theme.colors.primary};
      &:hover:not(:disabled) {
        background-color: ${theme.colors.primaryLight};
        color: ${theme.colors.primaryDark};
      }
    `}

  &:disabled {
    opacity: 0.45;
    cursor: not-allowed;
  }

  &:focus-visible {
    outline: 2px solid ${({ theme }) => theme.colors.primary};
    outline-offset: 2px;
  }
`;

export const IconButton: React.FC<IconButtonProps> = ({
  size = 'md',
  tone = 'neutral',
  label,
  children,
  type = 'button',
  ...props
}) => (
  <StyledIconButton
    $size={size}
    $tone={tone}
    type={type}
    aria-label={label}
    title={label}
    {...props}
  >
    {children}
  </StyledIconButton>
);
