import { useEffect, useMemo, useState } from 'react'
import type { ReactNode } from 'react'
import { Button, Card, Empty, Grid, Space, Typography } from '@arco-design/web-react'
import {
  IconBook,
  IconCheckCircle,
  IconCompass,
  IconFire,
  IconLink,
  IconMessage,
  IconRefresh,
  IconRobot,
  IconStar,
} from '@arco-design/web-react/icon'
import type { InboxItem, Project, ProjectWorkspace } from './projects/project-types'

const { Row, Col } = Grid
const { Title, Text, Paragraph } = Typography

type ExploreArticle = InboxItem & {
  project: Project
}

type DataSource = {
  name: string
  count: number
  icon: ReactNode
  color: string
}

export function WorkspaceExplorePage({
  workspaces,
  onSelectItem,
}: {
  workspaces: ProjectWorkspace[]
  onSelectItem: (title: string) => void
}) {
  const articles = useMemo(
    () =>
      workspaces.flatMap((workspace) =>
        workspace.inbox.map((item) => ({
          ...item,
          project: workspace.project,
        })),
      ),
    [workspaces],
  )
  const sources = useMemo(() => dataSources(articles), [articles])
  const [activeArticleID, setActiveArticleID] = useState<string | null>(articles[0]?.id ?? null)

  useEffect(() => {
    if (articles.length === 0) {
      setActiveArticleID(null)
      return
    }
    if (!activeArticleID || !articles.some((article) => article.id === activeArticleID)) {
      setActiveArticleID(articles[0].id)
    }
  }, [activeArticleID, articles])

  const selected = articles.find((article) => article.id === activeArticleID) ?? articles[0]

  return (
    <div className="workspace-explore-page overview-page">
      <div className="overview-head">
        <div>
          <Title heading={4}>探索</Title>
          <Text type="secondary">多个外部数据源的集中阅读页，采集文章、AI 总结并沉淀到项目。</Text>
        </div>
        <Space>
          <Button icon={<IconRefresh />}>同步数据源</Button>
          <Button type="primary" icon={<IconLink />}>
            添加数据源
          </Button>
        </Space>
      </div>

      <Row gutter={12} className="explore-source-row">
        {sources.map((source) => (
          <Col span={8} key={source.name}>
            <Card className="compact-card explore-source-card" bordered>
              <span className={`explore-source-icon ${source.color}`}>{source.icon}</span>
              <span className="explore-source-copy">
                <Text className="explore-source-name">{source.name}</Text>
                <Text type="secondary">{source.count} 条</Text>
              </span>
            </Card>
          </Col>
        ))}
      </Row>

      {selected ? (
        <section className="explore-reader-layout">
          <Card className="explore-article-list queue-section" bordered>
            <div className="explore-list-header">
              <Title heading={5}>{sourceName(selected)} - 最新文章</Title>
              <Space>
                <Button type="text" icon={<IconRefresh />} />
                <Button type="text" icon={<IconCheckCircle />} />
              </Space>
            </div>
            <div className="explore-list-body">
              {articles.map((article) => (
                <button
                  key={`${article.project.id}-${article.id}`}
                  className={article.id === selected.id ? 'explore-article-item active' : 'explore-article-item'}
                  onClick={() => {
                    setActiveArticleID(article.id)
                    onSelectItem(article.title)
                  }}
                >
                  <span className="explore-source-logo">{sourceInitial(sourceName(article))}</span>
                  <span className="explore-article-copy">
                    <Text type="secondary">
                      {sourceName(article)} · {article.time}
                    </Text>
                    <Text className="explore-article-title">{article.title}</Text>
                    <Text type="secondary" ellipsis={{ showTooltip: true }}>
                      {article.summary || '暂无摘要'}
                    </Text>
                  </span>
                </button>
              ))}
            </div>
          </Card>

          <Card className="explore-article-detail queue-section" bordered>
            <div className="explore-detail-toolbar">
              <Space>
                <Button type="text" icon={<IconCheckCircle />} />
                <Button type="text" icon={<IconStar />} />
                <Button type="text" icon={<IconBook />} />
                <Button type="text" icon={<IconMessage />} />
              </Space>
            </div>
            <article className="explore-article-body">
              <Title heading={2}>{selected.title}</Title>
              <Space className="explore-article-meta" wrap>
                <span className="explore-source-logo small">{sourceInitial(sourceName(selected))}</span>
                <Text type="secondary">{sourceName(selected)} - 最新文章</Text>
                <Text type="secondary">{selected.time}</Text>
              </Space>
              <div className="explore-avatar-strip">
                {workspaces.slice(0, 8).map((workspace) => (
                  <span key={workspace.project.id} style={{ background: workspace.project.color }}>
                    {workspace.project.short}
                  </span>
                ))}
                <span>+{Math.max(workspaces.length - 8, 0)}</span>
              </div>
              <Card className="explore-ai-summary" bordered>
                <Space>
                  <IconRobot />
                  <Text>AI 总结</Text>
                </Space>
                <Paragraph>
                  {selected.summary ||
                    '暂无正文摘要。同步数据源后，系统会在这里沉淀文章核心观点、风险点和可转化为项目计划的线索。'}
                </Paragraph>
              </Card>
              <blockquote>
                推荐：将外部文章中的项目机会、风险提示和资料线索归档到对应项目，形成可追踪的计划和知识资产。
              </blockquote>
            </article>
          </Card>
        </section>
      ) : (
        <Card className="queue-section" bordered>
          <Empty description="暂无数据源文章" />
        </Card>
      )}
    </div>
  )
}

function dataSources(articles: ExploreArticle[]): DataSource[] {
  const counts = new Map<string, number>()
  articles.forEach((article) => counts.set(sourceName(article), (counts.get(sourceName(article)) ?? 0) + 1))
  const iconSet = [
    { icon: <IconFire />, color: 'blue' },
    { icon: <IconCompass />, color: 'green' },
    { icon: <IconBook />, color: 'orange' },
  ]

  return Array.from(counts.entries())
    .slice(0, 3)
    .map(([name, count], index) => ({
      name,
      count,
      icon: iconSet[index]?.icon ?? <IconLink />,
      color: iconSet[index]?.color ?? 'blue',
    }))
}

function sourceName(article: ExploreArticle) {
  return article.meta?.replace(/^来源：/, '') || article.project.name
}

function sourceInitial(name: string) {
  return name.trim().slice(0, 1) || '源'
}
