import { forwardRef } from 'react'
import type { ButtonHTMLAttributes, ReactNode } from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
import { SendPlaneLine, StopLine, MicLine } from '../basic/icons-inline'

const sendButtonVariants = cva(
  'inline-flex items-center justify-center rounded-full p-1.5 transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-border focus-visible:ring-offset-2 focus-visible:ring-offset-bg-base disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition-transform active:scale-95 active:translate-y-px',
  {
    variants: {
      status: {
        normal:
          'SendButton-send bg-bg-highlight hover:bg-bg-highlight-hover active:opacity-80',
        generating:
          'bg-primary hover:bg-primary-hover active:opacity-80',
        recording:
          'SendButton-send bg-bg-highlight hover:bg-bg-highlight-hover active:opacity-80',
        stopRecording:
          'bg-error-bg hover:bg-error-bg-hover active:opacity-80',
      },
    },
    defaultVariants: {
      status: 'normal',
    },
  }
)

const sendButtonIconVariants = cva('inline-flex h-4 w-4 shrink-0 items-center justify-center [&>*]:block [&>*]:leading-none', {
  variants: {
    status: {
      normal: 'text-text-on-primary',
      generating: 'text-text-on-primary',
      recording: 'text-text-on-primary',
      stopRecording: 'text-error',
    },
  },
  defaultVariants: {
    status: 'normal',
  },
})

const iconClass = 'w-4 h-4'

export interface SendButtonProps
  extends ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof sendButtonVariants> {
  status?: 'normal' | 'generating' | 'recording' | 'stopRecording'
  /** 主库可注入 useIcon('send')；不传则用 registry 内联图标 */
  sendIcon?: ReactNode
  stopIcon?: ReactNode
  micIcon?: ReactNode
}

export const SendButton = forwardRef<HTMLButtonElement, SendButtonProps>(
  (
    {
      status = 'normal',
      disabled = false,
      className,
      sendIcon,
      stopIcon,
      micIcon,
      ...props
    },
    ref
  ) => {
    const defaultSend = sendIcon ?? <SendPlaneLine className={iconClass} />
    const defaultStop = stopIcon ?? <StopLine className={iconClass} />
    const defaultMic = micIcon ?? <MicLine className={iconClass} />
    const iconByStatus =
      status === 'normal'
        ? defaultSend
        : status === 'generating' || status === 'stopRecording'
          ? defaultStop
          : defaultMic

    return (
      <button
        ref={ref}
        type="button"
        className={sendButtonVariants({ status, className })}
        disabled={disabled}
        {...props}
      >
        <span className={sendButtonIconVariants({ status })}>
          {iconByStatus}
        </span>
      </button>
    )
  }
)

SendButton.displayName = 'SendButton'

export { sendButtonVariants, sendButtonIconVariants }
