import React, { useEffect, useMemo, useState } from 'react';
import { Table, Pagination, Space, Button, TablePaginationConfig, Input } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined, BulbOutlined, CloseOutlined } from '@ant-design/icons';
import { GuideTips } from '@/components/common';
import LocalStorage from '@/LocalStorage';
// 导入 GuideTips 配置
import { getGuideTipsConfig } from '@/config/guideTips';

import store from './store';
import ReviseDrawer from '../components/reviseDrawer';

interface KnowledgeRecord {
  knowledgeName: string;
  knowledgeId: string | number;
  length: string | number;
  appNames: string;
  documentSize: number;
  createTime: string;
  updateTime: string;
  status: string | number;
}

const RevisionToolList: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const { state, init, handleNameChange, onChangePagination } = store;
  const { reviseList, knowledgeName } = state;

  const [allupdateSliceDoc, setAllupdateSliceDoc] = useState<boolean>(false);
  const [singleUpdateSliceDoc, setSingleUpdateSliceDoc] = useState<boolean>(false);

  useEffect(() => {
    setLoading(true);
    const t = setTimeout(() => setLoading(false), 250);
    return () => clearTimeout(t);
  }, [state.page]);

  useEffect(() => {
    setAllupdateSliceDoc(LocalStorage.getStatusFlag('knowledge:revisionTool:all'));
    setSingleUpdateSliceDoc(LocalStorage.getStatusFlag('knowledge:revisionTool:single'));
    init();
  }, []);

  // 获取 GuideTips 配置
  const guideTipsConfig = getGuideTipsConfig('revisionTool');
  const [showGuide, setShowGuide] = React.useState<boolean>(() => localStorage.getItem('revisionToolGuideHidden') !== 'true');
  const hideGuide = () => { localStorage.setItem('revisionToolGuideHidden', 'true'); setShowGuide(false); };
  const [record, setRecord] = useState<KnowledgeRecord>({} as KnowledgeRecord);

  const columns: ColumnsType<KnowledgeRecord> = [
    {
      title: '知识库名称/ID', dataIndex: 'knowledgeName', width: 220,
      render: (text, record: any) => {
        return (
          <div>
            <div style={{ fontWeight: 600 }} className='cursor-pointer text-primary'>{text}</div>
            <div style={{ color: '#999', fontSize: 12, marginTop: 4 }}>ID: {record?.knowledgeId}</div>
          </div>
        );
      },
    },
    {
      title: '关联 RAG 应用', dataIndex: 'appNames', width: 180,
      render: (text) => (
        text.length ? text.map((item: string, index: number) => (
          <span key={index} className='mr-2'>{item}{index === text.length - 1 ? '' : ','}</span>
        )) : '-'
      )
    },
    { title: '使用空间', dataIndex: 'length', width: 120 },
    { title: '文件数量', dataIndex: 'documentSize', width: 120 },
    { title: '创建时间', dataIndex: 'createTime', width: 140 },
    { title: '更新时间', dataIndex: 'updateTime', width: 140 },
    {
      title: '操作',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 150,
      render: (val, record) => (
        singleUpdateSliceDoc ? (
          <Button type="link" onClick={() => { setOpenDrawer(true); setTitle(record.knowledgeName); setRecord(record); }}>
            当前知识修订
          </Button>
        ) : '-'
      ),
    }
  ];

  const paginationConfig: TablePaginationConfig = {
    showTotal: (total: number) => `共 ${total} 条`,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '50', '100'],
    showQuickJumper: true,
    current: state.page.page,
    pageSize: state.page.size,
    total: state.page.total,
    onChange: async (page, pageSize) => {
      await onChangePagination(page, pageSize);
    },
  };

  const [openDrawer, setOpenDrawer] = useState(false);
  const [title, setTitle] = useState('');

  return (
    <div className="page-container">
      {/* List Header */}
      <div className="list-header">
        <div className="list-header-title">
          <h1>知识库修订工具</h1>
          <p>管理和修订知识库内容</p>
        </div>
        <div className="list-header-actions">
          {allupdateSliceDoc && (
            <Button type="primary" onClick={() => { setOpenDrawer(true); setRecord({} as KnowledgeRecord); setTitle('全局修订工具'); }}>
              全局修订工具
            </Button>
          )}
        </div>
      </div>

      {/* GuideTips */}
      {showGuide && guideTipsConfig && (
        <GuideTips
          visible={true}
          title={guideTipsConfig.title}
          steps={guideTipsConfig.steps}
          onClose={hideGuide}
        />
      )}

      {/* 筛选 + 表格区域 - 共用一个 content-section */}
      <div className="content-section">
        {/* 筛选操作区域 */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <Space.Compact style={{ width: '300px' }}>
            <Input
              placeholder='请输入知识库名称进行搜索'
              value={knowledgeName}
              onChange={(e) => handleNameChange(e.target.value)}
            />
            <Button type="primary" onClick={() => { init() }}><SearchOutlined /></Button>
          </Space.Compact>
        </div>
        
        {/* 表格区域 */}
        <Table
          columns={columns}
          dataSource={reviseList}
          rowKey="knowledgeId"
          loading={loading}
          pagination={paginationConfig}
          scroll={{ x: 'max-content' }}
        />
      </div>

      {/* 修订工具弹窗 */}
      {<ReviseDrawer openDrawer={openDrawer} record={record} title={title} onClose={() => setOpenDrawer(false)} />}
    </div>
  );
};

export default RevisionToolList;
