import { forwardRef, useState } from 'react'
import type { HTMLAttributes, ButtonHTMLAttributes } from 'react'
import { cn } from '@/lib/utils'
import type { ReactNode } from 'react'
import { Button } from '../basic/button'
import { CloseLine, WarningLine } from '../basic/icons-inline'
import { Scrollbar } from '../basic/scrollbar'

export interface PermissionCardAction extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children'> {
  label: string
}

export interface PermissionCardProps extends HTMLAttributes<HTMLDivElement> {
  title?: string
  description?: string
  command: string
  commandIntent?: string
  isLoadingIntent?: boolean
  onClose?: () => void
  actions?: {
    deny?: PermissionCardAction
    allowOnce?: PermissionCardAction
  }
  closeIcon?: ReactNode
  warningIcon?: ReactNode
  /** 主库 i18n：展开/折叠按钮文案 */
  expandLabel?: string
  collapseLabel?: string
  commaLabel?: string
}

const COMMAND_COLLAPSE_THRESHOLD = 80

function omitLabel(a: PermissionCardAction | undefined): Omit<PermissionCardAction, 'label'> {
  if (!a) return {}
  const { label: _label, ...rest } = a
  void _label
  return rest
}

const defaultTitle = 'Permission required'
const defaultDescription = 'This action requires your permission.'
const defaultExpand = 'Expand'
const defaultCollapse = 'Collapse'
const defaultComma = ', '

export const PermissionCard = forwardRef<HTMLDivElement, PermissionCardProps>(
  (
    {
      title,
      description,
      command,
      commandIntent,
      isLoadingIntent = false,
      onClose,
      actions,
      className,
      closeIcon,
      warningIcon,
      expandLabel = defaultExpand,
      collapseLabel = defaultCollapse,
      commaLabel = defaultComma,
      ...props
    },
    ref
  ) => {
    const displayTitle = title ?? defaultTitle
    const displayDescription = description ?? defaultDescription
    const shouldCollapse = command.length > COMMAND_COLLAPSE_THRESHOLD
    const [isExpanded, setIsExpanded] = useState(!shouldCollapse)
    const defaultClose = closeIcon ?? <CloseLine className="h-3.5 w-3.5" />
    const defaultWarning = warningIcon ?? <WarningLine className="h-4 w-4" />

    return (
      <div
        ref={ref}
        className={cn(
          'relative rounded-lg border border-border-tertiary bg-bg-base p-3',
          className
        )}
        {...props}
      >
        {onClose && (
          <button
            type="button"
            onClick={onClose}
            className="absolute top-3 right-3 flex h-4 w-4 cursor-pointer items-center justify-center rounded-sm text-text-secondary transition-colors duration-200 hover:text-text focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-border"
            aria-label="Close"
          >
            {defaultClose}
          </button>
        )}

        <div className="mb-1 flex items-center gap-2">
          <div className="flex h-4 w-4 shrink-0 items-center justify-center text-warning">
            {defaultWarning}
          </div>
          <h3 className="min-w-0 flex-1 text-base leading-base font-semibold text-text">
            {displayTitle}
          </h3>
        </div>

        <p className="mb-2 ml-6 text-xs leading-xs text-text-tertiary">
          {isLoadingIntent ? (
            <span className="inline-flex items-center gap-1.5">
              <span className="inline-block h-3 w-3 animate-spin rounded-full border-2 border-text-tertiary border-t-transparent" />
              <span>{displayDescription}</span>
            </span>
          ) : (
            <>
              {displayDescription}
              {commandIntent && <span>{commaLabel}{commandIntent}</span>}
            </>
          )}
        </p>

        <div className="mb-4 ml-6">
          <div className="rounded p-2 bg-fill-tertiary">
            {isExpanded || !shouldCollapse ? (
              <div title={command}>
                <Scrollbar
                  scrollbarVisibility="auto"
                  maxHeight={240}
                  className="text-xs leading-xs font-medium text-text break-all"
                  style={{ fontFamily: 'Fira Code, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace' }}
                >
                  {command}
                </Scrollbar>
              </div>
            ) : (
              <div
                className="text-xs leading-xs font-medium text-text break-all line-clamp-2 overflow-hidden"
                style={{ fontFamily: 'Fira Code, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace' }}
                title={command}
              >
                {command}
              </div>
            )}
            {shouldCollapse && (
              <button
                type="button"
                onClick={() => setIsExpanded(!isExpanded)}
                className="mt-1 flex items-center gap-1 rounded-sm text-xs leading-xs text-text-tertiary hover:text-text transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-border"
              >
                {isExpanded ? collapseLabel : expandLabel}
              </button>
            )}
          </div>
        </div>

        <div className="flex items-center justify-end gap-2">
          {actions?.deny && (
            <Button variant="ghost" {...omitLabel(actions.deny)}>
              {actions.deny.label}
            </Button>
          )}
          {actions?.allowOnce && (
            <button
              type="button"
              className={cn(
                'rounded-full inline-flex items-center justify-center',
                'px-3 py-1 text-sm leading-sm font-medium',
                'text-text-on-primary bg-error',
                'cursor-pointer hover:opacity-90 active:opacity-95 transition-opacity',
                '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'
              )}
              {...omitLabel(actions.allowOnce)}
            >
              {actions.allowOnce.label}
            </button>
          )}
        </div>
      </div>
    )
  }
)

PermissionCard.displayName = 'PermissionCard'
