import React from 'react'
import type { Attachment } from '../../types'
import { getFileIconConfig } from '../../utils/fileIcons'

export interface AttachmentItemProps {
  attachment: Attachment
  onClick?: (attachment: Attachment) => void
}

/**
 * 附件展示组件
 */
export function AttachmentItem({ attachment, onClick }: AttachmentItemProps) {
  const handleClick = (e: React.MouseEvent) => {
    if (onClick) {
      e.preventDefault()
      onClick(attachment)
    }
  }

  const fileTypeFromMeta = attachment.file_type?.split('/')?.at(-1) ?? attachment.file_type
  const extFromName = attachment.file_name.split('.').pop() || ''
  const { icon: Icon, color } = getFileIconConfig(fileTypeFromMeta || extFromName)

  return (
    <a
      href={attachment.file_url}
      target={onClick ? undefined : '_blank'}
      rel="noopener noreferrer"
      onClick={handleClick}
      className="inline-flex items-center gap-2 px-3 py-4 rounded-lg bg-background border border-border hover:bg-muted/70 transition-colors cursor-pointer"
    >
      <span className="flex items-center justify-center w-7 h-7 rounded-md bg-primary/10">
        <Icon className={`w-4 h-4 ${color}`} />
      </span>
      <span className="text-sm text-foreground truncate max-w-[220px]">
        {attachment.file_name}
      </span>
    </a>
  )
}
