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

import store from './store';
import DataManagementMode from '../components/dataManagementMode';
import ExampleModel from '../components/exampleModel';
import { deleteDatasetApi } from '@/apis';

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

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

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

  const [deletedatasetManagement, setDeletedatasetManagement] = useState<boolean>(false);
  const [downloaddatasetManagement, setDownloaddatasetManagement] = useState<boolean>(false);
  const [userInfoAll, setUserInfoAll] = React.useState<any>({});

  useEffect(() => {
    init();
    setDeletedatasetManagement(LocalStorage.getStatusFlag('evaluationTool:datasetManagement:del'));
    setDownloaddatasetManagement(LocalStorage.getStatusFlag('evaluationTool:datasetManagement:download'));
    setUserInfoAll(LocalStorage.getUserInfo());

    const handleEvaluationTaskCreate = (e: any) => {
      if (e.detail && e.detail.platform === 'Management') {
        setOpenDataManagementMode(true);
      }
    };
    window.addEventListener('datasetManagement', handleEvaluationTaskCreate as EventListener);

    return () => {
      window.removeEventListener('datasetManagement', handleEvaluationTaskCreate as EventListener);
    };
  }, []);

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

  const columns: ColumnsType<KnowledgeRecord> = [
    {
      title: '数据集名称', dataIndex: 'name', width: 220,
      render: (text, record: any) => {
        return (
          <div>
            <div style={{ fontWeight: 600 }} className='cursor-pointer'>{text}</div>
          </div>
        );
      },
    },
    { title: '描述', dataIndex: 'description' },
    { title: '创建人', dataIndex: 'nickName', width: 120 },
    { title: '创建时机', dataIndex: 'createTime', width: 190 },
    {
      title: '操作',
      dataIndex: 'status',
      align: 'center',
      width: 150,
      render: (val, record: any) => (
        <Space size="small">
          {(downloaddatasetManagement || userInfoAll.id === record.createBy) && (
            <Button type="link" onClick={() => { window.open(record.url) }}>下载</Button>
          )}
          {(deletedatasetManagement || userInfoAll.id === record.createBy) && (
            <Button
              type="link"
              danger
              onClick={() => {
                Modal.confirm({
                  title: '删除',
                  content: `确定删除吗？`,
                  okType: 'danger',
                  onOk: async () => {
                    const res: any = await deleteDatasetApi(record.id);
                    if (res.code === 200) {
                      message.success('删除成功');
                      init();
                    }
                  }
                });
              }}
            >
              删除
            </Button>
          )}
        </Space>
      ),
    }
  ];

  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 [openDataManagementMode, setOpenDataManagementMode] = useState(false);
  const [ExampleModelVisible, setExampleModelVisible] = 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">
          <Button type="primary" onClick={() => setOpenDataManagementMode(true)}>
            创建数据集
          </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={{ marginBottom: 16 }}>
          <Radio.Group onChange={(e) => { handleModeChange(e.target.value); }} value={state.createBy} style={{ marginBottom: 8 }}>
            <Radio.Button value="">全部</Radio.Button>
            <Radio.Button value={state.myCreateBy}>我创建的</Radio.Button>
          </Radio.Group>
          <Space.Compact style={{ width: '300px', float: 'right' }}>
            <Input
              placeholder='请输入数据集名称'
              value={name}
              onChange={(e) => handleNameChange(e.target.value)}
            />
            <Button type="primary" onClick={() => { init() }}><SearchOutlined /></Button>
          </Space.Compact>
        </div>
        
        {/* 表格区域 */}
        <Table
          columns={columns}
          dataSource={reviseList}
          rowKey="id"
          loading={loading}
          pagination={paginationConfig}
          scroll={{ x: 'max-content' }}
        />
      </div>

      {/* 弹窗组件 */}
      {openDataManagementMode && (
        <DataManagementMode openDataManagementMode={openDataManagementMode} onCancel={() => { setOpenDataManagementMode(false); init(); }} />
      )}
      {<ExampleModel visible={ExampleModelVisible} onClose={() => { setExampleModelVisible(false); }} />}
    </div>
  );
};

export default DatasetManagementList;
