import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Table, Tag, Typography, Button, Space, App, Input } from 'antd'
import { ReloadOutlined, EyeOutlined, DeleteOutlined } from '@ant-design/icons'
import { getKnowledgeBases, deleteKnowledgeBase, type KnowledgeBase } from '@/services/knowledge-api'
import dayjs from 'dayjs'

const { Title, Text } = Typography

function KBPage() {
  const { modal, message } = App.useApp()
  const qc = useQueryClient()
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)

  const { data, isLoading } = useQuery({
    queryKey: ['knowledge-bases', page, pageSize],
    queryFn: () => getKnowledgeBases(page, pageSize),
  })

  const handleDelete = (kb: KnowledgeBase) => modal.confirm({
    title: '删除知识库', content: `确定删除「${kb.title}」？`, okType: 'danger',
    onOk: async () => { await deleteKnowledgeBase(kb.id); qc.invalidateQueries({ queryKey: ['knowledge-bases'] }); message.success('已删除') },
  })

  const columns = [
    { title: '名称', dataIndex: 'title', ellipsis: true, render: (t: string, r: KnowledgeBase) => <a onClick={() => message.info(`ID: ${r.id}`)}>{t}</a> },
    { title: '用户', dataIndex: ['user', 'nickname'], width: 120, render: (_: any, r: KnowledgeBase) => r.user?.nickname || r.user?.email || '-' },
    { title: '知识点', dataIndex: 'itemCount', width: 80, align: 'center' as const },
    { title: '状态', dataIndex: 'status', width: 80, render: (s: string) => <Tag color={s === 'active' ? 'green' : 'default'}>{s}</Tag> },
    { title: '创建时间', dataIndex: 'createdAt', width: 160, render: (d: string) => dayjs(d).format('YYYY-MM-DD HH:mm') },
    {
      title: '操作', width: 100,
      render: (_: any, r: KnowledgeBase) => (
        <Space>
          <Button type="link" size="small" icon={<EyeOutlined />}>详情</Button>
          <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(r)} />
        </Space>
      ),
    },
  ]

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <Title level={5} style={{ margin: 0 }}>知识库列表</Title>
        <Button icon={<ReloadOutlined />} onClick={() => qc.invalidateQueries({ queryKey: ['knowledge-bases'] })}>刷新</Button>
      </div>
      <Table
        dataSource={data?.items || []} columns={columns} rowKey="id" loading={isLoading}
        pagination={{ current: page, pageSize, total: data?.total || 0, showSizeChanger: true, showTotal: t => `共 ${t} 条`, onChange: (p, ps) => { setPage(p); setPageSize(ps) } }}
      />
    </div>
  )
}

export default function KnowledgeBasesPage() { return <App><KBPage /></App> }
