import { useState, useEffect } from 'react'
import { Card, Upload, Table, Button, Space, Select, Popconfirm, message, Tag, Input } from 'antd'
import { DeleteOutlined, ReloadOutlined, UploadOutlined, SearchOutlined, ClearOutlined } from '@ant-design/icons'
import useAuthStore from '../../stores/authStore'
import knowledgeService from '../../services/knowledgeService'
import KnowledgeTree from '../../components/KnowledgeTree/KnowledgeTree'

const { Dragger } = Upload

// source_type 枚举值（固定五类，不写死但供 Select 用）
const SOURCE_TYPE_OPTIONS = [
  { label: '全部类型', value: '' },
  { label: '杂志文章', value: 'military_report' },
  { label: '节目文稿', value: 'manuscript' },
  { label: '报题单', value: 'baoti' },
]

// source_type 中文标签
const SOURCE_TYPE_LABEL = {
  military_report: '杂志文章',
  manuscript: '节目文稿',
  baoti: '报题单',
  manual: '其他',
}

export default function KnowledgeBase() {
  const { user } = useAuthStore()
  const [items, setItems] = useState([])
  const [treeData, setTreeData] = useState([])
  const [loading, setLoading] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [sources, setSources] = useState([]) // 出处下拉选项
  const [sourceTypeFilter, setSourceTypeFilter] = useState('')
  const [sourceDetailFilter, setSourceDetailFilter] = useState('')
  const [selectedTreeNode, setSelectedTreeNode] = useState(null) // { type, detail }

  // 搜索状态
  const [searchQuery, setSearchQuery] = useState('')
  const [searchResults, setSearchResults] = useState([])
  const [searchLoading, setSearchLoading] = useState(false)

  const fetchItems = async () => {
    setLoading(true)
    try {
      const data = await knowledgeService.listItems(sourceTypeFilter || null)
      setItems(data)
    } catch {
      message.error('加载知识库失败')
    } finally {
      setLoading(false)
    }
  }

  const fetchTree = async () => {
    try {
      const data = await knowledgeService.getGroupedItems()
      setTreeData(data || [])
    } catch {
      // ignore
    }
  }

  const fetchSources = async () => {
    try {
      const data = await knowledgeService.listSources()
      // 接口返回 [{source: "航空知识 2026年第1期"}, ...]，提取 source 字段
      setSources(data.map(s => s.source).filter(Boolean))
    } catch {
      // ignore
    }
  }

  useEffect(() => {
    fetchItems()
    fetchTree()
    fetchSources()
  }, [sourceTypeFilter])

  // 上传
  const handleUpload = async (file) => {
    if (!file.name.endsWith('.md')) {
      message.warning('仅支持 .md 文件')
      return false
    }
    setUploading(true)
    try {
      const result = await knowledgeService.uploadFiles([file])
      const { uploaded, errors } = result
      if (uploaded.length > 0) {
        message.success(`成功入库 ${uploaded.length} 篇`)
        fetchItems()
        fetchTree()
      }
      if (errors.length > 0) {
        errors.forEach(e => message.error(`${e.file}: ${e.error}`))
      }
    } catch {
      message.error('上传失败')
    } finally {
      setUploading(false)
    }
    return false // 阻止默认上传行为
  }

  // 删除
  const handleDelete = async (id) => {
    try {
      await knowledgeService.deleteItem(id)
      message.success('删除成功')
      fetchItems()
      fetchTree()
    } catch {
      message.error('删除失败')
    }
  }

  // 搜索处理
  const handleSearch = async () => {
    if (!searchQuery.trim()) {
      setSearchResults([])
      return
    }
    setSearchLoading(true)
    try {
      const data = await knowledgeService.searchItems(searchQuery.trim())
      setSearchResults(data.results || [])
    } catch {
      message.error('搜索失败')
      setSearchResults([])
    } finally {
      setSearchLoading(false)
    }
  }

  // 清空搜索 → 恢复树形浏览（不丢树状态）
  const handleClearSearch = () => {
    setSearchQuery('')
    setSearchResults([])
  }

  // 树节点选中 → 联动过滤
  const handleNodeSelect = (node) => {
    setSelectedTreeNode(node)
  }

  // 根据树节点过滤列表
  const displayedItems = (() => {
    let result = items

    // 树节点过滤优先（覆盖原有 Select 筛选）
    if (selectedTreeNode) {
      const { type, detail } = selectedTreeNode
      result = result.filter(i => {
        if (i.source_type !== type) return false
        if (detail !== null) {
          // 按大类决定用哪个字段比对（节目文稿=author，杂志文章=source_detail）
          if (type === 'manuscript') {
            if (i.author !== detail) return false
          } else {
            // 杂志文章等用 source_detail
            if (i.source_detail !== detail) return false
          }
        }
        return true
      })
    } else if (sourceDetailFilter) {
      // 保留原有的 source_detail 筛选逻辑
      result = result.filter(i => i.source_detail === sourceDetailFilter)
    }

    return result
  })()

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 280,
      render: (text) => (
        <span style={{ fontWeight: 500, color: '#3b4a3b', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', display: 'block' }}>{text}</span>
      ),
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: 100,
      render: (val) => val || '-',
    },
    {
      title: '播出/发表时间',
      dataIndex: 'publish_date',
      key: 'publish_date',
      width: 160,
      render: (val) => val || '-',
    },
    {
      title: '出处',
      dataIndex: 'source_detail',
      key: 'source_detail',
      width: 200,
      render: (val) => val || '-',
    },
    {
      title: '类型',
      dataIndex: 'source_type',
      key: 'source_type',
      width: 96,
      render: (val) => (
        <Tag color="default" style={{ borderRadius: 8 }}>
          {SOURCE_TYPE_LABEL[val] || val}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 90,
      render: (_, record) => (
        <Popconfirm
          title="确认删除"
          description="删除后不可恢复，该篇及其向量将一并清除"
          onConfirm={() => handleDelete(record.id)}
          okText="确认删除"
          cancelText="取消"
          placement="left"
        >
          <Button size="small" danger icon={<DeleteOutlined />}>
            删除
          </Button>
        </Popconfirm>
      ),
    },
  ]

  return (
    <div style={{ maxWidth: 1200, padding: '12px 16px' }}>
      {/* 标题栏 */}
      <div style={{ marginBottom: 10 }}>
        <h2 style={{ margin: 0, fontSize: 20, fontWeight: 600, color: '#3b4a3b' }}>知识库</h2>
        <p style={{ margin: '4px 0 0', fontSize: 13, color: '#888' }}>上传 md 笔记 · 语义检索 · 报题参考</p>
      </div>

      {/* 上传区（收小为一行按钮） */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
        <Dragger
          accept=".md"
          multiple
          showUploadList={false}
          beforeUpload={handleUpload}
          disabled={uploading}
        >
          <Button icon={<UploadOutlined />} size="middle" style={{ borderRadius: 10 }}>
            {uploading ? '正在上传并生成向量…' : '上传 md 文件入库'}
          </Button>
        </Dragger>
        <span style={{ fontSize: 12, color: '#aaa' }}>支持批量上传，系统自动解析 yaml frontmatter 并生成语义向量</span>
      </div>

      {/* 搜索栏（搜索模式/浏览模式互斥，清空恢复树形浏览不丢状态） */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <Input
          placeholder="输入一段文字，语义搜索知识库…"
          value={searchQuery}
          onChange={e => setSearchQuery(e.target.value)}
          onPressEnter={handleSearch}
          style={{ width: 340, borderRadius: 10 }}
          prefix={<SearchOutlined style={{ color: '#aaa' }} />}
          suffix={
            searchQuery ? (
              <ClearOutlined
                style={{ color: '#aaa', cursor: 'pointer' }}
                onClick={handleClearSearch}
              />
            ) : null
          }
        />
        <Button
          icon={<SearchOutlined />}
          onClick={handleSearch}
          loading={searchLoading}
          style={{ borderRadius: 10 }}
        >
          搜索
        </Button>
        {searchQuery && (
          <span style={{ fontSize: 12, color: '#888' }}>
            {searchResults.length > 0
              ? `找到 ${searchResults.length} 条相关结果`
              : '无相关结果'}
          </span>
        )}
      </div>

      {/* 搜索结果列表（搜索模式显示，浏览模式隐藏） */}
      {searchQuery && searchResults.length > 0 && (
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 13, color: '#666', marginBottom: 8, fontWeight: 500 }}>
            搜索结果
          </div>
          {searchResults.map(item => (
            <Card
              key={item.id}
              size="small"
              style={{ borderRadius: 10, marginBottom: 8 }}
              bodyStyle={{ padding: '12px 16px' }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 14, color: '#3b4a3b', marginBottom: 4 }}>
                    {item.title}
                  </div>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 }}>
                    <Tag color="default" style={{ borderRadius: 6, fontSize: 12 }}>
                      {SOURCE_TYPE_LABEL[item.source_type] || item.source_type}
                    </Tag>
                    {item.author && (
                      <span style={{ fontSize: 12, color: '#888' }}>作者：{item.author}</span>
                    )}
                    {item.source_detail && (
                      <span style={{ fontSize: 12, color: '#888' }}>出处：{item.source_detail}</span>
                    )}
                  </div>
                  <div
                    style={{
                      fontSize: 12,
                      color: '#555',
                      background: '#f5f5f5',
                      borderRadius: 6,
                      padding: '6px 10px',
                      lineHeight: 1.6,
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      display: '-webkit-box',
                      WebkitLineClamp: 3,
                      WebkitBoxOrient: 'vertical',
                    }}
                  >
                    {item.snippet}
                  </div>
                </div>
                  <div style={{
                    marginLeft: 16,
                    minWidth: 56,
                    textAlign: 'center',
                    background: item.similarity >= 0.7 ? '#e6f4ff' : '#f5f5f5',
                    borderRadius: 8,
                    padding: '4px 8px',
                  }}>
                    <div style={{ fontSize: 18, fontWeight: 700, color: item.similarity >= 0.7 ? '#1677ff' : '#666' }}>
                      {Math.max(0, Math.round(item.similarity * 100))}%
                    </div>
                    <div style={{ fontSize: 11, color: '#888' }}>相关度</div>
                  </div>
              </div>
            </Card>
          ))}
        </div>
      )}

      {/* 主体：左侧树 + 右侧列表（flex 左右并列，宽度稳定） */}
      <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        {/* 左侧树 */}
        <Card
          style={{ borderRadius: 14, width: 280, flexShrink: 0 }}
          bodyStyle={{ padding: 0, height: '100%' }}
        >
          <KnowledgeTree
            treeData={treeData}
            onNodeSelect={handleNodeSelect}
            selectedKey={selectedTreeNode ? `${selectedTreeNode.type}${selectedTreeNode.detail ? '|' + selectedTreeNode.detail : ''}` : 'all'}
          />
        </Card>

        {/* 右侧列表 + 筛选栏 */}
        <div style={{ flex: 1, minWidth: 0 }}>
          {/* 筛选栏 */}
          <Card style={{ borderRadius: 14, marginBottom: 12 }}>
            <Space size="middle" wrap>
              <span style={{ fontSize: 14, color: '#666' }}>筛选：</span>
              <Select
                placeholder="按类型"
                options={SOURCE_TYPE_OPTIONS}
                value={sourceTypeFilter}
                onChange={val => { setSourceTypeFilter(val); setSourceDetailFilter(''); setSelectedTreeNode(null) }}
                style={{ width: 140 }}
                allowClear
              />
              <Select
                placeholder="按出处"
                options={[{ label: '全部出处', value: '' }, ...sources.map(s => ({ label: s, value: s }))]}
                value={sourceDetailFilter}
                onChange={val => { setSourceDetailFilter(val); setSelectedTreeNode(null) }}
                style={{ width: 200 }}
                allowClear
              />
              <Button
                icon={<ReloadOutlined />}
                onClick={() => { fetchItems(); fetchTree() }}
                size="small"
              >
                刷新
              </Button>
            </Space>
          </Card>

          {/* 列表 */}
          <Card style={{ borderRadius: 14 }}>
            <Table
              columns={columns}
              dataSource={displayedItems}
              rowKey="id"
              loading={loading}
              pagination={{ pageSize: 10, size: 'small' }}
              locale={{ emptyText: '暂无知识库条目，上传 md 文件开始入库' }}
            />
          </Card>
        </div>
      </div>
    </div>
  )
}