import { useEffect, useState } from 'react'
import { Alert, Badge, Button, Divider, Input, Layout, Modal, Space, Typography } from '@arco-design/web-react'
import { IconApps, IconDashboard, IconMore, IconPlus, IconSettings } from '@arco-design/web-react/icon'
import { ProjectIcon } from './project-icon'
import type { ChannelKey, ProjectChannel, ProjectWorkspace, WorkbenchView } from './project-types'

const { Sider } = Layout
const { Title, Text } = Typography
const { TextArea } = Input

export type ProjectSettingsUpdate = {
  projectId: string
  name: string
  identifier: string
  icon: string
  background: string
  description: string
}

export function ProjectSidebar({
  activeView,
  activeWorkspace,
  activeChannel,
  onSelectChannel,
  onSelectItem,
  onUpdateProject,
}: {
  activeView: WorkbenchView
  activeWorkspace: ProjectWorkspace
  activeChannel: ChannelKey
  onSelectChannel: (key: ChannelKey) => void
  onSelectItem: (title: string) => void
  onUpdateProject: (update: ProjectSettingsUpdate) => Promise<void>
}) {
  const workspaceMode = activeView === 'workspace'
  const channels = activeWorkspace.channels
  const [settingsOpen, setSettingsOpen] = useState(false)
  const [settingsSaving, setSettingsSaving] = useState(false)
  const [settingsError, setSettingsError] = useState('')
  const [draft, setDraft] = useState({
    name: activeWorkspace.project.name,
    identifier: activeWorkspace.project.identifier,
    icon: activeWorkspace.project.icon,
    background: activeWorkspace.project.background,
    description: activeWorkspace.project.description,
  })

  useEffect(() => {
    if (!settingsOpen) return
    setSettingsError('')
    setDraft({
      name: activeWorkspace.project.name,
      identifier: activeWorkspace.project.identifier,
      icon: activeWorkspace.project.icon,
      background: activeWorkspace.project.background,
      description: activeWorkspace.project.description,
    })
  }, [activeWorkspace.project, settingsOpen])

  return (
    <Sider className="channel-sidebar" width={248}>
      <div className="project-title">
        <Space>
          {workspaceMode ? <IconApps /> : <ProjectIcon className="project-title-icon" icon={activeWorkspace.project.icon} />}
          <Title heading={5}>{workspaceMode ? '工作台' : activeWorkspace.project.name}</Title>
        </Space>
        <Button aria-label="编辑项目设置" icon={<IconSettings />} size="mini" onClick={() => setSettingsOpen(true)} />
      </div>

      <div className="channel-list">
        {workspaceMode ? (
          <>
            <button className="channel-button active">
              <span className="channel-left"><IconDashboard /><Text>工作台总览</Text></span>
            <Badge count={channels.length} />
            </button>
            <button className="channel-button">
              <span className="channel-left"><IconApps /><Text>全部项目</Text></span>
              <IconMore />
            </button>
          </>
        ) : (
          <>
            {channels.flatMap((channel) => {
              const items = [renderChannelButton(channel, activeChannel, onSelectChannel)]
              if (channel.key === 'cron') {
                items.push(
                  <button
                    key="new-channel"
                    className={activeChannel === 'new-channel' ? 'channel-button active' : 'channel-button'}
                    onClick={() => onSelectChannel('new-channel')}
                  >
                    <span className="channel-left"><IconPlus /><Text>新建频道</Text></span>
                    <IconMore />
                  </button>,
                )
              }
              return items
            })}
          </>
        )}
      </div>

      <Divider />
      <section className="recent-sessions">
        <Text className="section-title">最近会话</Text>
        {activeWorkspace.recentSessions.slice(0, 4).map((session) => (
          <button key={session.id} onClick={() => onSelectItem(session.title)}>
            <Text>{session.title}</Text>
            <Text type="secondary">{session.time}</Text>
          </button>
        ))}
      </section>

      <Modal
        className="action-modal"
        title="编辑项目"
        visible={settingsOpen}
        confirmLoading={settingsSaving}
        maskClosable={!settingsSaving}
        cancelButtonProps={{ disabled: settingsSaving }}
        onCancel={() => {
          if (!settingsSaving) setSettingsOpen(false)
        }}
        onOk={async () => {
          setSettingsSaving(true)
          setSettingsError('')
          try {
            await onUpdateProject({
              projectId: activeWorkspace.project.id,
              name: draft.name.trim() || activeWorkspace.project.name,
              identifier: draft.identifier.trim(),
              icon: draft.icon.trim(),
              background: draft.background.trim(),
              description: draft.description.trim(),
            })
            setSettingsOpen(false)
          } catch (error) {
            setSettingsError(error instanceof Error ? error.message : '项目设置保存失败，请稍后重试')
          } finally {
            setSettingsSaving(false)
          }
        }}
      >
        <Space direction="vertical" size={12} className="action-form">
          {settingsError && <Alert className="project-settings-error" type="error" content={settingsError} />}
          <label>
            <Text>名称</Text>
            <Input value={draft.name} onChange={(name) => setDraft((value) => ({ ...value, name }))} />
          </label>
          <label>
            <Text>标识</Text>
            <Input value={draft.identifier} onChange={(identifier) => setDraft((value) => ({ ...value, identifier }))} />
          </label>
          <label>
            <Text>图标</Text>
            <Input value={draft.icon} onChange={(icon) => setDraft((value) => ({ ...value, icon }))} />
          </label>
          <label>
            <Text>背景</Text>
            <Input value={draft.background} onChange={(background) => setDraft((value) => ({ ...value, background }))} />
          </label>
          <label>
            <Text>简介</Text>
            <TextArea rows={4} value={draft.description} onChange={(description) => setDraft((value) => ({ ...value, description }))} />
          </label>
        </Space>
      </Modal>
    </Sider>
  )
}

function renderChannelButton(channel: ProjectChannel, activeChannel: ChannelKey, onSelectChannel: (key: ChannelKey) => void) {
  return (
    <button
      key={channel.id}
      className={activeChannel === channel.key ? 'channel-button active' : 'channel-button'}
      onClick={() => onSelectChannel(channel.key)}
    >
      <span className="channel-left">{channel.icon}<Text>{channel.label}</Text></span>
      {channel.key === 'overview' ? null : channel.count !== undefined ? <Badge className="channel-badge-muted" count={channel.count} maxCount={999} /> : <IconMore />}
    </button>
  )
}
