import { Button, Card, Input, Space, Typography } from '@arco-design/web-react'
import {
  IconArrowUp,
  IconAttachment,
  IconPlusCircle,
  IconRobot,
} from '@arco-design/web-react/icon'
import type { AISession, ProjectWorkspace } from './project-types'

const { Title, Text } = Typography

export function ProjectAi({ activeWorkspace, onSelectItem }: { activeWorkspace: ProjectWorkspace; onSelectItem: (title: string) => void }) {
  const { aiSessions } = activeWorkspace
  const groupedSessions = groupSessions(aiSessions)

  return (
    <div className="project-channel-page project-ai-page overview-page">
      <div className="agent-chat-shell">
        <Card className="agent-session-list queue-section" bordered>
          <Button className="agent-new-chat" icon={<IconPlusCircle />}>
            开启新对话
          </Button>

          <div className="agent-session-groups">
            {groupedSessions.length ? (
              groupedSessions.map((group) => (
                <section className="agent-session-group" key={group.label}>
                  <Text type="secondary">{group.label}</Text>
                  {group.items.map((session, index) => (
                    <button
                      className={index === 0 && group.label === groupedSessions[0]?.label ? 'agent-session active' : 'agent-session'}
                      key={session.id}
                      onClick={() => onSelectItem(session.title)}
                    >
                      {session.title}
                    </button>
                  ))}
                </section>
              ))
            ) : (
              <Text type="secondary">暂无对话</Text>
            )}
          </div>
        </Card>

        <Card className="agent-chat-panel queue-section" bordered>
          <div className="agent-chat-main">
            <Title heading={2}>选择专家，开始对话</Title>
          </div>
          <div className="agent-composer">
            <Input.TextArea placeholder="给 DeepSeek 发送消息" autoSize={{ minRows: 3, maxRows: 6 }} />
            <div className="agent-composer-footer">
              <Button className="agent-model-chip" icon={<IconRobot />}>
                DeepSeek V4.0 Flash
              </Button>
              <Space>
                <Button type="text" icon={<IconAttachment />} />
                <Button className="agent-send-button" type="primary" shape="circle" icon={<IconArrowUp />} />
              </Space>
            </div>
          </div>
        </Card>
      </div>
    </div>
  )
}

function groupSessions(sessions: AISession[]) {
  const labels = ['今天', '昨天', '7 天内']
  return labels.map((label) => ({
    label,
    items: sessions.filter((session, index) => session.time.includes(label) || (!labels.some((item) => session.time.includes(item)) && labels.indexOf(label) === fallbackGroupIndex(index))),
  })).filter((group) => group.items.length > 0)
}

function fallbackGroupIndex(index: number) {
  if (index === 0) return 0
  if (index === 1) return 1
  return 2
}
