import React, { useState, useEffect } from 'react'
import { AppIcon, WelcomeFile, WelcomeNew } from '../Icons'
import { recentFilesRepository } from '../../db/recentFilesRepository'
import { getFileName } from '../../lib/fileUtils'

interface WelcomeScreenProps {
  onOpen: () => void
  onNew: () => void
  onOpenRecent?: (filePath: string) => void
}

export const WelcomeScreen = React.memo(function WelcomeScreen({ onOpen, onNew, onOpenRecent }: WelcomeScreenProps) {
  const [recentFiles, setRecentFiles] = useState<string[]>([])

  useEffect(() => {
    recentFilesRepository.getAll(10).then((files: string[]) => {
      setRecentFiles(files)
    })
  }, [])

  return (
    <div id="welcome-screen" role="main" aria-label="欢迎页面">
      <div className="welcome-content">
        <div className="welcome-icon" aria-hidden="true">
          <AppIcon size={80} />
        </div>
        <h1>欢迎使用 MarkLite</h1>
        <p>一款轻量级的 Markdown 编辑器</p>
        <div className="welcome-actions" role="group" aria-label="快速操作">
          <button className="welcome-btn primary" onClick={onOpen} aria-label="打开文件">
            <WelcomeFile size={20} />
            打开文件
          </button>
          <button className="welcome-btn secondary" onClick={onNew} aria-label="新建文件">
            <WelcomeNew size={20} />
            新建文件
          </button>
        </div>

        {recentFiles.length > 0 && (
          <div className="welcome-recent">
            <h3>最近打开</h3>
            <div className="recent-list" role="list" aria-label="最近打开的文件">
              {recentFiles.map((filePath: string) => (
                <button
                  key={filePath}
                  className="recent-item"
                  onClick={() => onOpenRecent?.(filePath)}
                  title={filePath}
                  role="listitem"
                  aria-label={`打开 ${getFileName(filePath)}`}
                >
                  <span className="recent-icon" aria-hidden="true">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
                      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                      <polyline points="14 2 14 8 20 8" />
                    </svg>
                  </span>
                  <span className="recent-name">{getFileName(filePath)}</span>
                  <span className="recent-path">{filePath}</span>
                </button>
              ))}
            </div>
          </div>
        )}

        <div className="welcome-tips" role="note" aria-label="使用提示">
          <p>💡 提示：可以直接拖拽 .md 文件到窗口打开</p>
          <p>⌨️ 快捷键：Ctrl+O 打开 | Ctrl+S 保存 | Ctrl+F 搜索 | Ctrl+1/2 视图</p>
        </div>
      </div>
    </div>
  )
})

WelcomeScreen.displayName = 'WelcomeScreen'
