import type { CSSProperties } from 'react'
import { Badge, Button, Layout, Space } from '@arco-design/web-react'
import { IconCompass, IconPlus } from '@arco-design/web-react/icon'
import type { Project, WorkbenchView } from './project-types'

const { Sider } = Layout

export function ProjectRail({
  activeProject,
  projects,
  activeView,
  onSelectWorkspace,
  onSelectWorkspaceExplore,
  onSelectProject,
  onCreateProject,
}: {
  activeProject: Project
  projects: Project[]
  activeView: WorkbenchView
  onSelectWorkspace: () => void
  onSelectWorkspaceExplore: () => void
  onSelectProject: (project: Project) => void
  onCreateProject: () => void
}) {
  return (
    <Sider className="project-rail" width={96}>
      <Button
        className={activeView === 'workspace' ? 'dashboard-button active' : 'dashboard-button'}
        icon={<img className="brand-icon rail-brand-icon" src="/senlinai-icon.svg" alt="" aria-hidden="true" />}
        onClick={onSelectWorkspace}
        aria-label="森林AI 工作台"
        title="森林AI 工作台"
      />
      <Button
        className={activeView === 'workspace-explore' ? 'dashboard-button active' : 'dashboard-button'}
        icon={<IconCompass />}
        onClick={onSelectWorkspaceExplore}
        aria-label="探索"
        title="探索"
      />
      <Space className="project-stack" direction="vertical" size={12}>
        {projects.map((project) => (
          <Badge key={project.id} count={project.badge} dot={false} className={project.urgent ? 'project-badge urgent' : 'project-badge'}>
            <button
              className={activeView === 'project' && activeProject.id === project.id ? 'project-button active' : 'project-button'}
              onClick={() => onSelectProject(project)}
              style={{ '--project-color': project.color } as CSSProperties}
              title={project.name}
            >
              {projectNameLabel(project.name)}
            </button>
          </Badge>
        ))}
      </Space>
      <Button className="create-project" aria-label="新建项目" icon={<IconPlus />} title="新建项目" onClick={onCreateProject} />
    </Sider>
  )
}

function projectNameLabel(name: string) {
  const characters = Array.from(name.trim())
  const limit = characters.some((character) => /\p{Script=Han}/u.test(character)) ? 2 : 4
  return characters.slice(0, limit).join('')
}
