import type { ReactNode } from 'react'
import { CollapsibleCard } from '../basic/collapsible-card'
import { IconButton } from '../basic/icon-button'
import { TerminalBoxLine, ExternalLinkLine } from '../basic/icons-inline'

const ICON_CLASS = 'w-[var(--font-size-sm)] h-[var(--font-size-sm)] shrink-0 text-text-secondary'

export interface TerminalCodeBlockPartProps {
  command?: string
  output?: string
  autoRanCommand?: string
  className?: string
  headerIcon?: ReactNode
  externalLinkIcon?: ReactNode
}

const defaultHeaderIcon = <TerminalBoxLine className={ICON_CLASS} />
const defaultExternalLinkIcon = <ExternalLinkLine className={ICON_CLASS} />

export function TerminalCodeBlockPart({
  command,
  output,
  autoRanCommand,
  className,
  headerIcon,
  externalLinkIcon,
}: TerminalCodeBlockPartProps) {
  const displayCommand = autoRanCommand ?? (command != null ? `Auto-Ran command: ${command}` : 'Terminal')

  return (
    <CollapsibleCard
      headerIcon={headerIcon ?? defaultHeaderIcon}
      headerTitle={<span className="font-normal">{displayCommand}</span>}
      headerRight={
        <IconButton
          variant="iconOnly"
          size="sm"
          icon={externalLinkIcon ?? defaultExternalLinkIcon}
          aria-label="Open in terminal"
          className="!min-h-0 !min-w-0 h-[var(--font-size-sm)] w-[var(--font-size-sm)] text-text-secondary hover:text-text [&_svg]:w-[var(--font-size-sm)] [&_svg]:h-[var(--font-size-sm)]"
        />
      }
      contentPadding="0"
      className={className}
    >
      <div className="flex flex-col gap-0">
        {command != null && command !== '' && (
          <div className="px-2 py-1.5">
            <div className="flex items-start gap-2">
              <span className="font-mono text-xs text-text shrink-0">$</span>
              <pre className="m-0 flex-1 overflow-x-auto text-left font-mono text-xs leading-xs whitespace-pre text-text bg-transparent scrollbar-auto">
                <code>{command}</code>
              </pre>
            </div>
          </div>
        )}
        {output != null && output !== '' && (
          <div className="px-2 py-1.5 overflow-x-auto text-left scrollbar-auto">
            <pre className="m-0 p-0 font-mono text-xs leading-xs whitespace-pre-wrap break-all text-text-tertiary bg-transparent">
              {output}
            </pre>
          </div>
        )}
      </div>
    </CollapsibleCard>
  )
}

TerminalCodeBlockPart.displayName = 'TerminalCodeBlockPart'
export const TerminalOutputCard = TerminalCodeBlockPart
export type TerminalOutputCardProps = TerminalCodeBlockPartProps
