import { memo, useState } from 'react'
import { cn } from '@/lib/utils'
import type { ReactNode } from 'react'
import { TimeLine, CheckboxCircleLine, CloseCircleLine, ArrowDownSLine } from '../basic/icons-inline'
import { Scrollbar } from '../basic/scrollbar'

export type ToolInvocationStatus = 'running' | 'success' | 'error'

export interface ToolInvocationCardProps {
  toolName: string
  params?: string
  status: ToolInvocationStatus
  response?: string
  defaultExpanded?: boolean
  statusText?: string
  className?: string
  timeIcon?: ReactNode
  checkboxCircleIcon?: ReactNode
  closeCircleIcon?: ReactNode
  arrowDownIcon?: ReactNode
  /** @deprecated Use arrowDownIcon. */
  arrowRightIcon?: ReactNode
  runningText?: string
  ranText?: string
  failedText?: string
  responseLabel?: string
}

/* 左侧状态图标随 token：容器 text-xs 使 1em = var(--font-size-xs)，图标 size-[1em] 继承 */
const statusIconClass = 'size-[1em] shrink-0'
const timeClass = `${statusIconClass} text-text-tertiary`
const checkboxClass = `${statusIconClass} text-success`
const closeCircleClass = `${statusIconClass} text-text-tertiary`
const arrowClass = 'w-3.5 h-3.5 text-text-tertiary transition-all duration-200'

export const ToolInvocationCard = memo(function ToolInvocationCard({
  toolName,
  params,
  status,
  response,
  defaultExpanded = false,
  statusText: statusTextProp,
  className,
  timeIcon,
  checkboxCircleIcon,
  closeCircleIcon,
  arrowDownIcon,
  arrowRightIcon,
  runningText = 'Running',
  ranText = 'Ran',
  failedText = 'Failed',
  responseLabel = 'Response',
}: ToolInvocationCardProps) {
  const [isExpanded, setIsExpanded] = useState(defaultExpanded)

  const hasResponse = response != null && response.length > 0
  const isRunning = status === 'running'
  const isSuccess = status === 'success'
  const isError = status === 'error'

  const defaultStatusText = isRunning ? runningText : isSuccess ? ranText : failedText
  const statusText = statusTextProp !== undefined ? statusTextProp : defaultStatusText
  const showStatusText = statusText !== ''

  const defaultTime = timeIcon ?? <TimeLine className={timeClass} />
  const defaultCheck = checkboxCircleIcon ?? <CheckboxCircleLine className={checkboxClass} />
  const defaultCloseCircle = closeCircleIcon ?? <CloseCircleLine className={closeCircleClass} />
  const defaultArrow = arrowDownIcon ?? arrowRightIcon ?? <ArrowDownSLine className={arrowClass} />

  return (
    <div className={cn('flex flex-col', className)}>
      <div
        onClick={() => hasResponse && !isRunning && setIsExpanded(!isExpanded)}
        className={cn(
          'group flex items-center gap-1.5 min-h-5',
          hasResponse && !isRunning && 'cursor-pointer hover:opacity-80 transition-opacity'
        )}
      >
        <div className="shrink-0 flex items-center justify-center text-xs">
          {isRunning && defaultTime}
          {isSuccess && defaultCheck}
          {isError && defaultCloseCircle}
        </div>
        {showStatusText && (
          <span className="text-xs leading-xs text-text-tertiary shrink-0">{statusText}</span>
        )}
        <span className="text-xs leading-xs text-text-secondary shrink-0">{toolName}</span>
        {params != null && params !== '' && (
          <span
            className="text-xs leading-xs text-text-tertiary min-w-0 shrink truncate"
            title={params}
          >
            {params}
          </span>
        )}
        {hasResponse && !isRunning && (
          <div
            className={cn(
              'shrink-0 inline-flex items-center justify-center',
              'opacity-0 group-hover:opacity-100',
              isExpanded && '!opacity-100',
              isExpanded ? 'rotate-180' : 'rotate-0'
            )}
          >
            {defaultArrow}
          </div>
        )}
      </div>

      {hasResponse && isExpanded && (
        <div className="mt-1 ml-4.5 rounded-md border border-border-tertiary bg-bg-base overflow-hidden font-mono text-xs leading-xs">
          <div className="text-text-tertiary px-2 pt-1 pb-0 leading-xs">
            {responseLabel}
          </div>
          <Scrollbar
            scrollbarVisibility="auto"
            maxHeight={208}
            className="px-2 pb-1 leading-xs"
          >
            <pre
              className={cn(
                'whitespace-pre-wrap break-words leading-xs',
                isError ? 'text-error' : 'text-text-tertiary'
              )}
            >
              {response}
            </pre>
          </Scrollbar>
        </div>
      )}
    </div>
  )
})

ToolInvocationCard.displayName = 'ToolInvocationCard'
export const ToolCallCard = ToolInvocationCard
export type ToolCallCardProps = ToolInvocationCardProps
export type ToolCallStatus = ToolInvocationStatus
