import * as React from 'react'
import type { Tab } from './types'
import { OutlinePanel } from './OutlinePanel'
import type { OutlineItem } from './markdown'

type DirEntry = { name: string; path: string; kind: 'file' | 'dir' }

type Props = {
  sidebarTab: 'files' | 'history' | 'outline'
  onSidebarTabChange: (tab: 'files' | 'history' | 'outline') => void
  browseDir: string
  dirEntries: DirEntry[]
  dirError: string | null
  parentDisabled: boolean
  onNavigateDir: (path: string) => void
  onOpenFile: (path: string) => void
  onContextMenu: (e: React.MouseEvent, path: string, kind: 'file' | 'dir') => void
  fileHistory: string[]
  onHistoryOpen: (path: string) => void
  onHistoryContextMenu: (e: React.MouseEvent, path: string) => void
  outlineItems: OutlineItem[]
  onOutlineSelect: (item: OutlineItem) => void
  tabs: Tab[]
  activeId: string
}

export function Sidebar({
  sidebarTab,
  onSidebarTabChange,
  browseDir,
  dirEntries,
  dirError,
  parentDisabled,
  onNavigateDir,
  onOpenFile,
  onContextMenu,
  fileHistory,
  onHistoryOpen,
  onHistoryContextMenu,
  outlineItems,
  onOutlineSelect,
  tabs,
  activeId
}: Props): React.ReactElement {
  const [filter, setFilter] = React.useState('')

  const filteredEntries = React.useMemo(() => {
    if (!filter) return dirEntries
    const lower = filter.toLowerCase()
    return dirEntries.filter((e) => e.name.toLowerCase().includes(lower))
  }, [dirEntries, filter])

  const activeFilePath = React.useMemo(() => {
    const t = tabs.find((x) => x.id === activeId)
    return t?.filePath ?? null
  }, [tabs, activeId])

  return (
    <div className="sidebar-content">
      <div className="sidebar-tabs">
        <button
          type="button"
          className={sidebarTab === 'files' ? 'on' : ''}
          onClick={() => onSidebarTabChange('files')}
        >
          文件
        </button>
        <button
          type="button"
          className={sidebarTab === 'history' ? 'on' : ''}
          onClick={() => onSidebarTabChange('history')}
        >
          历史
        </button>
        <button
          type="button"
          className={sidebarTab === 'outline' ? 'on' : ''}
          onClick={() => onSidebarTabChange('outline')}
        >
          大纲
        </button>
      </div>

      {sidebarTab === 'files' ? (
        <FilePanel
          browseDir={browseDir}
          dirEntries={filteredEntries}
          dirError={dirError}
          parentDisabled={parentDisabled}
          onNavigateDir={onNavigateDir}
          onOpenFile={onOpenFile}
          onContextMenu={onContextMenu}
          filter={filter}
          onFilterChange={setFilter}
          activeFilePath={activeFilePath}
        />
      ) : sidebarTab === 'history' ? (
        <HistoryPanel
          fileHistory={fileHistory}
          onOpen={onHistoryOpen}
          onContextMenu={onHistoryContextMenu}
        />
      ) : (
        <OutlinePanel items={outlineItems} onSelect={onOutlineSelect} />
      )}
    </div>
  )
}

function FilePanel({
  browseDir,
  dirEntries,
  dirError,
  parentDisabled,
  onNavigateDir,
  onOpenFile,
  onContextMenu,
  filter,
  onFilterChange,
  activeFilePath
}: {
  browseDir: string
  dirEntries: DirEntry[]
  dirError: string | null
  parentDisabled: boolean
  onNavigateDir: (path: string) => void
  onOpenFile: (path: string) => void
  onContextMenu: (e: React.MouseEvent, path: string, kind: 'file' | 'dir') => void
  filter: string
  onFilterChange: (v: string) => void
  activeFilePath: string | null
}): React.ReactElement {
  return (
    <div className="file-panel">
      <div className="path-row">
        <button
          type="button"
          className="path-btn"
          disabled={parentDisabled}
          onClick={() => {
            const parts = browseDir.replace(/\\/g, '/').replace(/\/+$/, '').split('/')
            parts.pop()
            onNavigateDir(parts.join('/') || '/')
          }}
          title="上级目录"
        >
          ←
        </button>
        <span className="path-label" title={browseDir}>{browseDir}</span>
      </div>
      <div className="file-filter">
        <input
          type="text"
          className="file-filter-input"
          placeholder="筛选文件..."
          value={filter}
          onChange={(e) => onFilterChange(e.target.value)}
        />
      </div>
      <div className="dir-list">
        {dirError ? (
          <div className="sidebar-empty">
            <div className="sidebar-empty-icon">⚠️</div>
            <div className="sidebar-empty-text">{dirError}</div>
          </div>
        ) : dirEntries.length === 0 ? (
          <div className="sidebar-empty">
            <div className="sidebar-empty-icon">📂</div>
            <div className="sidebar-empty-text">此目录为空</div>
            <div className="sidebar-empty-hint">拖放 Markdown 文件到窗口打开</div>
          </div>
        ) : (
          dirEntries.map((e) => (
            <div
              key={e.path}
              className={`dir-item${e.kind === 'file' && e.path === activeFilePath ? ' dir-item--active' : ''}`}
              onClick={() => {
                if (e.kind === 'dir') onNavigateDir(e.path)
                else onOpenFile(e.path)
              }}
              onContextMenu={(ev) => onContextMenu(ev, e.path, e.kind)}
            >
              <span className="dir-item-icon">{e.kind === 'dir' ? '📁' : '📄'}</span>
              <span className="dir-item-name">{e.name}</span>
            </div>
          ))
        )}
      </div>
    </div>
  )
}

function HistoryPanel({
  fileHistory,
  onOpen,
  onContextMenu
}: {
  fileHistory: string[]
  onOpen: (path: string) => void
  onContextMenu: (e: React.MouseEvent, path: string) => void
}): React.ReactElement {
  return (
    <div className="history-panel">
      {fileHistory.length === 0 ? (
        <div className="sidebar-empty">
          <div className="sidebar-empty-icon">🕐</div>
          <div className="sidebar-empty-text">暂无历史记录</div>
          <div className="sidebar-empty-hint">打开文件后会自动记录</div>
        </div>
      ) : (
        fileHistory.map((p) => (
          <div
            key={p}
            className="history-item"
            onClick={() => onOpen(p)}
            onContextMenu={(ev) => onContextMenu(ev, p)}
          >
            <span className="history-item-icon">📄</span>
            <div className="history-item-body">
              <span className="history-item-name">{p.split(/[/\\]/).pop()}</span>
              <span className="history-item-path">{p}</span>
            </div>
          </div>
        ))
      )}
    </div>
  )
}