import { useEffect, useMemo, useState } from 'react'
import type { ReactNode } from 'react'
import { Alert, Button, Card, Empty, Grid, Input, Modal, Select, Space, Typography } from '@arco-design/web-react'
import {
  IconBook,
  IconCheckCircle,
  IconCompass,
  IconDelete,
  IconEdit,
  IconFile,
  IconLink,
  IconRefresh,
  IconStar,
  IconStorage,
} from '@arco-design/web-react/icon'
import type { InboxItem, Project, ProjectWorkspace } from './projects/project-types'

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

type BuiltinDataSourceID = 'all' | 'manual' | 'requirements' | 'architecture'
type DataSourceID = BuiltinDataSourceID | `custom:${number}`
type DataSourceKind = 'manual' | 'link' | 'rss'

type ExploreArticle = InboxItem & {
  project: Project
  sourceID: BuiltinDataSourceID
}

type DataSourceConfig = {
  id: DataSourceID
  name: string
  icon: ReactNode
  color: string
  kind: DataSourceKind
  url: string
  description: string
}

type DataSourceCard = DataSourceConfig & {
  count: number
}

type SourceDraft = {
  name: string
  kind: DataSourceKind
  url: string
  description: string
}

const INITIAL_SOURCES: DataSourceConfig[] = [
  { id: 'all', name: '全部', icon: <IconStorage />, color: 'blue', kind: 'manual', url: '', description: '全部探索内容' },
  { id: 'manual', name: '手动收集', icon: <IconCompass />, color: 'green', kind: 'manual', url: '', description: '手动收集的文章与线索' },
  { id: 'requirements', name: '需求文档', icon: <IconFile />, color: 'orange', kind: 'link', url: '', description: '产品需求与业务文档' },
  { id: 'architecture', name: '架构讨论', icon: <IconBook />, color: 'purple', kind: 'link', url: '', description: '架构方案与系统设计讨论' },
]

const EMPTY_SOURCE_DRAFT: SourceDraft = {
  name: '',
  kind: 'link',
  url: '',
  description: '',
}

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,
          sourceID: detectSource(item),
        })),
      ),
    [workspaces],
  )
  const [sourceConfigs, setSourceConfigs] = useState<DataSourceConfig[]>(INITIAL_SOURCES)
  const [activeSourceID, setActiveSourceID] = useState<DataSourceID>('all')
  const [sourceModalMode, setSourceModalMode] = useState<'add' | 'edit' | null>(null)
  const [editingSourceID, setEditingSourceID] = useState<DataSourceID | null>(null)
  const [sourceDraft, setSourceDraft] = useState<SourceDraft>(EMPTY_SOURCE_DRAFT)
  const [sourceError, setSourceError] = useState('')
  const filteredArticles = useMemo(
    () => (activeSourceID === 'all' ? articles : articles.filter((article) => article.sourceID === activeSourceID)),
    [activeSourceID, articles],
  )
  const sources = useMemo(() => dataSources(articles, sourceConfigs), [articles, sourceConfigs])
  const [activeArticleID, setActiveArticleID] = useState<string | null>(filteredArticles[0]?.id ?? null)

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

  const selected = filteredArticles.find((article) => article.id === activeArticleID) ?? filteredArticles[0]
  const activeSource = sourceByID(sources, activeSourceID)
  const selectedSource = selected ? sourceByID(sources, selected.sourceID) : activeSource

  function openAddSource() {
    setEditingSourceID(null)
    setSourceDraft(EMPTY_SOURCE_DRAFT)
    setSourceError('')
    setSourceModalMode('add')
  }

  function openEditSource(source: DataSourceCard) {
    setEditingSourceID(source.id)
    setSourceDraft({
      name: source.name,
      kind: source.kind,
      url: source.url,
      description: source.description,
    })
    setSourceError('')
    setSourceModalMode('edit')
  }

  function saveSource() {
    const name = sourceDraft.name.trim()
    if (!name) {
      setSourceError('请输入数据源名称')
      return
    }
    const nextDraft = { ...sourceDraft, name, url: sourceDraft.url.trim(), description: sourceDraft.description.trim() }
    if (sourceModalMode === 'edit' && editingSourceID) {
      setSourceConfigs((current) => current.map((source) => source.id === editingSourceID ? { ...source, ...nextDraft } : source))
    } else {
      setSourceConfigs((current) => [
        ...current,
        {
          id: `custom:${Date.now()}`,
          ...nextDraft,
          icon: sourceIcon(nextDraft.kind),
          color: sourceColor(nextDraft.kind),
        },
      ])
    }
    setSourceModalMode(null)
  }

  function deleteSource(source: DataSourceCard) {
    Modal.confirm({
      title: `删除“${source.name}”数据源？`,
      content: '删除后，该数据源将从探索页移除。',
      okButtonProps: { status: 'danger' },
      onOk: () => {
        setSourceConfigs((current) => current.filter((item) => item.id !== source.id))
        if (activeSourceID === source.id) setActiveSourceID('all')
      },
    })
  }

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

      <Row gutter={10} className="explore-source-row">
        {sources.map((source) => (
          <Col span={6} key={source.id}>
            <Card
              className={activeSourceID === source.id ? 'compact-card explore-source-card active' : 'compact-card explore-source-card'}
              bordered
              onClick={() => setActiveSourceID(source.id)}
            >
              <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>
              {source.id !== 'all' ? (
                <span className="explore-source-actions" onClick={(event) => event.stopPropagation()}>
                  <Button aria-label={`编辑${source.name}`} type="text" size="mini" icon={<IconEdit />} onClick={() => openEditSource(source)} />
                  <Button aria-label={`删除${source.name}`} type="text" size="mini" status="danger" icon={<IconDelete />} onClick={() => deleteSource(source)} />
                </span>
              ) : null}
            </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}>
                <Space size={6}>
                  <span className={`explore-source-icon mini ${activeSource.color}`}>{activeSource.icon}</span>
                  <span>{activeSource.name}</span>
                </Space>
              </Title>
              <Button type="text" icon={<IconRefresh />} />
            </div>
            <div className="explore-list-body">
              {filteredArticles.map((article) => {
                const articleSource = sourceByID(sources, article.sourceID)
                return (
                  <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 ${articleSource.color}`}>
                      {sourceInitial(articleSource.name)}
                    </span>
                    <span className="explore-article-copy">
                      <Text type="secondary">
                        {articleSource.name} · {article.time}
                      </Text>
                      <Text className="explore-article-title">{article.title}</Text>
                      <Text className="explore-article-summary" 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">
              <Title heading={5}>{selected.title}</Title>
              <Space>
                <Button type="text" icon={<IconCheckCircle />} />
                <Button type="text" icon={<IconStar />} />
                <Button type="text" icon={<IconBook />} />
              </Space>
            </div>
            <article className="explore-article-body">
              <Space className="explore-article-meta" wrap>
                <span className={`explore-source-logo small ${selectedSource.color}`}>
                  {sourceInitial(selectedSource.name)}
                </span>
                <Text type="secondary">{selectedSource.name}</Text>
                <Text type="secondary">{selected.project.name}</Text>
                <Text type="secondary">{selected.time}</Text>
              </Space>
              <Paragraph className="explore-article-content">{selected.summary || '暂无正文'}</Paragraph>
              <blockquote>
                推荐：将外部文章中的项目机会、风险提示和资料线索归档到对应项目，形成可追踪的计划和知识资产。
              </blockquote>
            </article>
          </Card>
        </section>
      ) : (
        <Card className="queue-section" bordered>
          <Empty description="暂无数据源文章" />
        </Card>
      )}

      <Modal
        className="explore-source-modal"
        title={sourceModalMode === 'edit' ? '编辑数据源' : '添加数据源'}
        visible={sourceModalMode !== null}
        okText="保存"
        cancelText="取消"
        onCancel={() => setSourceModalMode(null)}
        onOk={saveSource}
      >
        <Space direction="vertical" size={12} className="action-form">
          {sourceError && <Alert type="error" content={sourceError} />}
          <label>
            <Text>数据源名称</Text>
            <Input value={sourceDraft.name} placeholder="例如：行业资讯" onChange={(name) => setSourceDraft((current) => ({ ...current, name }))} />
          </label>
          <label>
            <Text>数据源类型</Text>
            <Select value={sourceDraft.kind} onChange={(kind) => setSourceDraft((current) => ({ ...current, kind }))}>
              <Select.Option value="link">网页链接</Select.Option>
              <Select.Option value="rss">RSS 订阅</Select.Option>
              <Select.Option value="manual">手动收集</Select.Option>
            </Select>
          </label>
          <label>
            <Text>链接地址</Text>
            <Input value={sourceDraft.url} placeholder="https://example.com/feed" onChange={(url) => setSourceDraft((current) => ({ ...current, url }))} />
          </label>
          <label>
            <Text>说明</Text>
            <TextArea rows={4} value={sourceDraft.description} placeholder="数据源用途或内容范围" onChange={(description) => setSourceDraft((current) => ({ ...current, description }))} />
          </label>
        </Space>
      </Modal>
    </div>
  )
}

function dataSources(articles: ExploreArticle[], configs: DataSourceConfig[]): DataSourceCard[] {
  const counts = new Map<DataSourceID, number>(configs.map((source) => [source.id, source.id === 'all' ? articles.length : 0]))
  articles.forEach((article) => counts.set(article.sourceID, (counts.get(article.sourceID) ?? 0) + 1))
  return configs.map((source) => ({ ...source, count: counts.get(source.id) ?? 0 }))
}

function sourceByID(sources: DataSourceCard[], id: DataSourceID): DataSourceCard {
  return sources.find((source) => source.id === id) ?? sources[0]
}

function detectSource(article: InboxItem): BuiltinDataSourceID {
  const text = `${article.title} ${article.meta} ${article.tag} ${article.summary}`
  if (/架构|技术方案|系统设计|architecture/i.test(text)) return 'architecture'
  if (/需求|PRD|产品文档|requirement/i.test(text)) return 'requirements'
  return 'manual'
}

function sourceIcon(kind: DataSourceKind) {
  if (kind === 'rss') return <IconStorage />
  if (kind === 'manual') return <IconCompass />
  return <IconLink />
}

function sourceColor(kind: DataSourceKind) {
  if (kind === 'rss') return 'orange'
  if (kind === 'manual') return 'green'
  return 'blue'
}

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