import React from 'react';
import MuiButton from '@mui/material/Button';
import type { ButtonProps as MuiButtonProps } from '@mui/material/Button';
import CircularProgress from '@mui/material/CircularProgress';

// ─── Types ───────────────────────────────────────────────────────────────────

/** Props for the FA Button component */
export interface ButtonProps extends MuiButtonProps {
  /** Show a loading spinner and disable interaction */
  loading?: boolean;
  /** Add underline decoration (useful for text variant link-style buttons) */
  underline?: boolean;
}

// ─── Component ───────────────────────────────────────────────────────────────

/**
 * Primary interactive element for the FA design system.
 *
 * Wraps MUI Button with FA brand tokens, custom sizes (xs/sm/md/lg),
 * loading state, and underline support for text-variant buttons.
 *
 * Variant mapping from design:
 * - `contained` + `primary` — Primary CTA (copper fill)
 * - `soft` + `primary` — Secondary/Brand (warm tonal fill)
 * - `soft` + `secondary` — Secondary/Grey (neutral tonal fill)
 * - `outlined` + `primary` — Outlined brand (copper border)
 * - `outlined` + `secondary` — Outlined grey (neutral border)
 * - `text` + `primary` — Ghost / text button (copper text)
 * - `text` + `secondary` — Ghost secondary (grey text)
 *
 * **Accessibility**: Icon-only buttons (no visible text) require an
 * `aria-label` prop. Without it, screen readers announce nothing.
 * Example: `<Button startIcon={<DeleteIcon />} aria-label="Delete item" />`
 */
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  (
    {
      loading = false,
      underline = false,
      disabled,
      children,
      variant = 'contained',
      size = 'medium',
      sx,
      ...props
    },
    ref,
  ) => {
    return (
      <MuiButton
        ref={ref}
        variant={variant}
        size={size}
        disabled={loading || disabled}
        aria-busy={loading || undefined}
        sx={[
          underline &&
            variant === 'text' && {
              textDecoration: 'underline',
              textUnderlineOffset: '3px',
              '&:hover': { textDecoration: 'underline' },
            },
          ...(Array.isArray(sx) ? sx : [sx]),
        ]}
        {...props}
      >
        {children}
        {loading && (
          <>
            <CircularProgress size={16} color="inherit" thickness={3} aria-hidden sx={{ ml: 1 }} />
            <span
              style={{
                position: 'absolute',
                width: 1,
                height: 1,
                padding: 0,
                margin: -1,
                overflow: 'hidden',
                clip: 'rect(0, 0, 0, 0)',
                whiteSpace: 'nowrap',
                borderWidth: 0,
              }}
            >
              Loading
            </span>
          </>
        )}
      </MuiButton>
    );
  },
);

Button.displayName = 'Button';
export default Button;
