import { IconFile, IconFileImage, IconFilePdf, IconFolder } from '@arco-design/web-react/icon'
import type { NoteSource } from './project-types'

export type ProjectFileItem = NoteSource | {
  id: string
  title: string
  type: string
  updated: string
  owner: string
  source?: string
}

export function ProjectFileGrid({
  items,
  onSelectItem,
  compact = false,
}: {
  items: ProjectFileItem[]
  onSelectItem: (title: string) => void
  compact?: boolean
}) {
  return (
    <div className={compact ? 'project-file-grid compact' : 'project-file-grid'}>
      {items.map((item) => {
        const fileKind = inferFileKind(item)
        return (
          <button className="project-file-tile" key={item.id} onClick={() => onSelectItem(item.title)}>
            <span className={`project-file-icon ${fileKind.kind}`}>{fileIcon(fileKind.kind)}</span>
            <span className="project-file-copy">
              <span className="project-file-name">{item.title}</span>
              <span className="project-file-type">{fileKind.label}</span>
              <span className="project-file-meta">{fileKind.meta}</span>
            </span>
          </button>
        )
      })}
    </div>
  )
}

function inferFileKind(item: ProjectFileItem) {
  const value = `${item.title} ${item.type} ${item.source ?? ''}`.toLowerCase()
  if (item.type === 'folder' || item.source === 'folder') return { kind: 'folder', label: '文件夹', meta: item.updated }
  if (value.includes('pdf')) return { kind: 'pdf', label: 'PDF 文档', meta: item.updated }
  if (value.includes('png') || value.includes('jpg') || value.includes('jpeg') || value.includes('图片')) return { kind: 'image', label: '图片文件', meta: item.updated }
  if (value.includes('excel') || value.includes('xlsx') || value.includes('表')) return { kind: 'sheet', label: '表格文件', meta: item.updated }
  if (value.includes('word') || value.includes('doc') || value.includes('文档')) return { kind: 'doc', label: '文档', meta: item.updated }
  if (value.includes('markdown') || value.includes('笔记')) return { kind: 'note', label: 'Markdown 笔记', meta: item.updated }
  return { kind: 'file', label: item.type || '文件', meta: item.updated }
}

function fileIcon(kind: string) {
  if (kind === 'folder') return <IconFolder />
  if (kind === 'pdf') return <IconFilePdf />
  if (kind === 'image') return <IconFileImage />
  return <IconFile />
}
