import { useState, useRef, useEffect, type MouseEvent as ReactMouseEvent } from 'react'
import { open as openDialog } from '@tauri-apps/plugin-dialog'
import type { Config, TerminalTab } from '../types'
import type { View } from '../App'
import { FileTree } from './FileTree'
import { UsagePanel } from './UsagePanel'
import {
  IconAgents,
  IconBell,
  IconBook,
  IconChevronLeft,
  IconChevronRight,
  IconClose,
  IconFile,
  IconFolder,
  IconGear,
  IconGlobe,
  IconList,
  IconPlug,
  IconPlus,
  IconSearch,
  IconSyringe,
  IconTerminal
} from './Icons'

interface Props {
  config: Config
  view: View
  tabs: TerminalTab[]
  onSelectProject: (path: string) => void
  onAddProject: (path: string) => void
  onRemoveProject: (path: string) => void
  onNavigate: (view: View) => void
  /** 把文本填入当前可见终端（无终端时为 null） */
  onInsertPath: ((text: string) => void) | null
  /** 等待输入的会话数（收件箱徽标） */
  attentionCount: number
  onOpenInbox: () => void
  /** 文件树单击文件打开预览 */
  onPreviewFile: (path: string) => void
}

type SidebarMode = 'projects' | 'files'

export function Sidebar({
  config,
  view,
  tabs,
  onSelectProject,
  onAddProject,
  onRemoveProject,
  onNavigate,
  onInsertPath,
  attentionCount,
  onOpenInbox,
  onPreviewFile
}: Props) {
  const [mode, setMode] = useState<SidebarMode>('projects')
  const [collapsed, setCollapsed] = useState(false)
  const rootRef = useRef<HTMLDivElement>(null)
  // 侧栏宽度可拖拽，跨重启保留（localStorage）
  const [width, setWidth] = useState<number>(() => {
    const v = Number(localStorage.getItem('ccgui.sidebarWidth'))
    return v >= 160 && v <= 480 ? v : 210
  })
  useEffect(() => {
    localStorage.setItem('ccgui.sidebarWidth', String(width))
  }, [width])

  // 拖动右缘调整宽度：侧栏左缘贴窗口左侧，新宽度即指针到左缘的距离
  const startResize = (e: ReactMouseEvent) => {
    e.preventDefault()
    const left = rootRef.current?.getBoundingClientRect().left ?? 0
    const onMove = (ev: MouseEvent) => {
      setWidth(Math.min(480, Math.max(160, ev.clientX - left)))
    }
    const onUp = () => {
      window.removeEventListener('mousemove', onMove)
      window.removeEventListener('mouseup', onUp)
    }
    window.addEventListener('mousemove', onMove)
    window.addEventListener('mouseup', onUp)
  }

  const currentProject = view.kind === 'project' ? view.path : null

  const pickFolder = async () => {
    const picked = await openDialog({ directory: true, title: '选择项目目录' })
    if (typeof picked === 'string' && picked) onAddProject(picked)
  }

  if (collapsed) {
    return (
      <div className="sidebar collapsed">
        <button className="btn ghost small" title="展开侧边栏" onClick={() => setCollapsed(false)}>
          <IconChevronRight />
        </button>
        <button
          className="btn ghost small"
          title="项目"
          onClick={() => {
            setMode('projects')
            setCollapsed(false)
          }}
        >
          <IconFolder />
        </button>
        <button
          className="btn ghost small"
          title="文件"
          onClick={() => {
            setMode('files')
            setCollapsed(false)
          }}
        >
          <IconFile />
        </button>
        <div style={{ flex: 1 }} />
        <button className="btn ghost small" title="待处理" onClick={onOpenInbox} style={{ position: 'relative' }}>
          <IconBell />
          {attentionCount > 0 && <span className="inbox-badge">{attentionCount}</span>}
        </button>
        <button className="btn ghost small" title="搜索会话" onClick={() => onNavigate({ kind: 'search' })}>
          <IconSearch />
        </button>
        <button className="btn ghost small" title="指令库" onClick={() => onNavigate({ kind: 'commands' })}>
          <IconList />
        </button>
        <button className="btn ghost small" title="规则库" onClick={() => onNavigate({ kind: 'rules' })}>
          <IconBook />
        </button>
        {config.settings.mobileRelayEnabled && (
          <button className="btn ghost small" title="隧道管理" onClick={() => onNavigate({ kind: 'tunnels' })}>
            <IconGlobe />
          </button>
        )}
        <button className="btn ghost small" title="API 注入" onClick={() => onNavigate({ kind: 'apiInject' })}>
          <IconSyringe />
        </button>
        <button className="btn ghost small" title="Agents" onClick={() => onNavigate({ kind: 'agents' })}>
          <IconAgents />
        </button>
        <button className="btn ghost small" title="设置" onClick={() => onNavigate({ kind: 'settings' })}>
          <IconGear />
        </button>
      </div>
    )
  }

  return (
    <div className="sidebar" ref={rootRef} style={{ width }}>
      <div className="side-resizer right" onMouseDown={startResize} title="拖动调整侧栏宽度" />
      <div className="sidebar-tabs">
        <button
          className={`sidebar-tab ${mode === 'projects' ? 'active' : ''}`}
          onClick={() => setMode('projects')}
        >
          项目
        </button>
        <button
          className={`sidebar-tab ${mode === 'files' ? 'active' : ''}`}
          onClick={() => setMode('files')}
        >
          文件
        </button>
        <div style={{ flex: 1 }} />
        {mode === 'projects' && (
          <button className="btn ghost small" title="添加项目" onClick={() => void pickFolder()}>
            <IconPlus />
          </button>
        )}
        <button className="btn ghost small" title="折叠侧边栏" onClick={() => setCollapsed(true)}>
          <IconChevronLeft />
        </button>
      </div>

      {mode === 'projects' ? (
        <div className="sidebar-list">
          {config.projects.map((p) => {
            const active = view.kind === 'project' && view.path === p.path
            const running = tabs.some((t) => t.projectPath === p.path && t.status !== 'exited')
            const attention = tabs.some(
              (t) => t.projectPath === p.path && (t.status === 'attention' || t.unread)
            )
            return (
              <div
                key={p.path}
                className={`sidebar-item ${active ? 'active' : ''}`}
                title={p.path}
                onClick={() => onSelectProject(p.path)}
              >
                <IconFolder style={{ flexShrink: 0, color: 'var(--text-dim)' }} />
                <span className="item-name">{p.name}</span>
                {attention ? (
                  <span className="dot attention" />
                ) : running ? (
                  <span className="dot working" />
                ) : null}
                <button
                  className="item-x"
                  title="移除项目（不删除目录与会话记录）"
                  onClick={(e) => {
                    e.stopPropagation()
                    onRemoveProject(p.path)
                  }}
                >
                  <IconClose width={11} height={11} />
                </button>
              </div>
            )
          })}
          {config.projects.length === 0 && (
            <div style={{ padding: '14px 10px', color: 'var(--text-faint)', fontSize: 12 }}>
              点击右上角 + 添加项目目录
            </div>
          )}
        </div>
      ) : currentProject ? (
        <FileTree projectPath={currentProject} onInsertPath={onInsertPath} onPreviewFile={onPreviewFile} />
      ) : (
        <div style={{ padding: '14px 10px', color: 'var(--text-faint)', fontSize: 12, flex: 1 }}>
          先在「项目」中选择一个项目
        </div>
      )}

      <UsagePanel />

      <div className="sidebar-footer">
        <div
          className={`sidebar-item span-2 ${view.kind === 'search' ? 'active' : ''}`}
          onClick={() => onNavigate({ kind: 'search' })}
        >
          <IconSearch style={{ flexShrink: 0, color: 'var(--text-dim)' }} />
          <span className="item-name">搜索会话</span>
        </div>
        <div className="sidebar-item" onClick={onOpenInbox}>
          <IconBell
            style={{ flexShrink: 0, color: attentionCount > 0 ? 'var(--warn)' : 'var(--text-dim)' }}
          />
          <span className="item-name">待处理</span>
          {attentionCount > 0 && <span className="badge accent">{attentionCount}</span>}
        </div>
        <div className="sidebar-item static" title="运行中的终端会话数量">
          <IconTerminal style={{ flexShrink: 0, color: 'var(--text-dim)' }} />
          <span className="item-name">活跃</span>
          <span className="badge">{tabs.filter((t) => t.status !== 'exited').length}</span>
        </div>
        <div
          className={`sidebar-item ${view.kind === 'commands' ? 'active' : ''}`}
          onClick={() => onNavigate({ kind: 'commands' })}
        >
          <IconList style={{ flexShrink: 0, color: 'var(--text-dim)' }} />
          <span className="item-name">指令库</span>
        </div>
        <div
          className={`sidebar-item ${view.kind === 'rules' ? 'active' : ''}`}
          onClick={() => onNavigate({ kind: 'rules' })}
        >
          <IconBook style={{ flexShrink: 0, color: 'var(--text-dim)' }} />
          <span className="item-name">规则库</span>
        </div>
        <div
          className={`sidebar-item ${view.kind === 'mcp' ? 'active' : ''}`}
          onClick={() => onNavigate({ kind: 'mcp' })}
        >
          <IconPlug style={{ flexShrink: 0, color: 'var(--text-dim)' }} />
          <span className="item-name">MCP</span>
        </div>
        {config.settings.mobileRelayEnabled && (
          <div
            className={`sidebar-item ${view.kind === 'tunnels' ? 'active' : ''}`}
            onClick={() => onNavigate({ kind: 'tunnels' })}
          >
            <IconGlobe style={{ flexShrink: 0, color: 'var(--text-dim)' }} />
            <span className="item-name">隧道</span>
          </div>
        )}
        <div
          className={`sidebar-item ${view.kind === 'apiInject' ? 'active' : ''}`}
          onClick={() => onNavigate({ kind: 'apiInject' })}
        >
          <IconSyringe style={{ flexShrink: 0, color: 'var(--text-dim)' }} />
          <span className="item-name">API 注入</span>
        </div>
        <div
          className={`sidebar-item ${view.kind === 'agents' ? 'active' : ''}`}
          onClick={() => onNavigate({ kind: 'agents' })}
        >
          <IconAgents style={{ flexShrink: 0, color: 'var(--text-dim)' }} />
          <span className="item-name">Agents</span>
        </div>
        <div
          className={`sidebar-item ${view.kind === 'settings' ? 'active' : ''}`}
          onClick={() => onNavigate({ kind: 'settings' })}
        >
          <IconGear style={{ flexShrink: 0, color: 'var(--text-dim)' }} />
          <span className="item-name">设置</span>
        </div>
      </div>
    </div>
  )
}
