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

import store from './store';
import CreateTaskMode from '../components/CreateTaskMode';
import IndicatorRag from '../components/indicatorRag';
import EvaluationTaskHistory from '../components/evaluationTaskHistory';
import { deleteEvaluationApi, beginEvaluationApi } from '@/apis';
import { Tooltip } from 'antd/lib';

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

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

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

  const [deleteEvaluationTask, setDeleteEvaluationTask] = useState<boolean>(false);
  const [startEvaluationTask, setStartEvaluationTask] = useState<boolean>(false);
  const [prewEvaluationTask, setPrewEvaluationTask] = useState<boolean>(false);
  const [userInfoAll, setUserInfoAll] = React.useState<any>({});
  const [openEvaluationTaskHistory, setOpenEvaluationTaskHistory] = useState<boolean>(false);

  useEffect(() => {
    init();
    setDeleteEvaluationTask(LocalStorage.getStatusFlag('evaluationTool:evaluationTask:del'));
    setStartEvaluationTask(LocalStorage.getStatusFlag('evaluationTool:evaluationTask:start'));
    setPrewEvaluationTask(LocalStorage.getStatusFlag('evaluationTool:evaluationTask:prew'));
    setUserInfoAll(LocalStorage.getUserInfo());

    const handleEvaluationTaskCreate = (e: any) => {
      if (e.detail && e.detail.platform === 'Task') {
        setOpenCreateTaskMode(true);
      }
    };
    const handlEvaluationTaskHistoryCreate = (e: any) => {
      if (e.detail && e.detail.platform === 'evaluationTaskHistory') {
        setOpenEvaluationTaskHistory(true);
      }
    };

    window.addEventListener('evaluationTask', handleEvaluationTaskCreate as EventListener);
    window.addEventListener('evaluationTaskHistory', handlEvaluationTaskHistoryCreate as EventListener);

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

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

  const onBeginEvaluationApi = async (record: any) => {
    const res: any = await beginEvaluationApi({ ...record });
    if (res.code === 200) {
      message.success('评测任务启动成功');
      init();
    }
  };

  const columns: ColumnsType<KnowledgeRecord> = [
    {
      title: '任务名称/ID', dataIndex: 'taskId', width: 220,
      render: (text, record: any) => {
        return (
          <div>
            {(prewEvaluationTask || userInfoAll.id === record.createBy) ? (
              <div style={{ fontWeight: 600 }} className='cursor-pointer text-primary' onClick={() => {
                setOpenIndicatorRag(true);
                setRecord(record);
              }}>{record.taskName}</div>
            ) : (
              <div style={{ fontWeight: 600 }}>{record.taskName}</div>
            )}
            <div style={{ color: '#999', fontSize: 12, marginTop: 4 }}>ID: {record?.taskId}</div>
          </div>
        );
      },
    },
    {
      title: '状态', dataIndex: 'status', width: 120,
      render: (text) => {
        let color = '#52c41a';
        let statusText = '';
        if (text === '0') {
          color = '';
          statusText = '未执行';
        } else if (text === '1') {
          return <Spin size="small" />;
        } else if (text === '2') {
          color = '#52c41a';
          statusText = '成功';
        } else if (text === '3') {
          color = '';
          statusText = '失败';
        }
        return <span style={{ color }}>{statusText}</span>;
      }
    },
    { title: '模型服务', dataIndex: 'model', width: 120 },
    { title: '类型', dataIndex: 'evaluationType', width: 140 },
    { title: '数据集', dataIndex: 'datesetName', width: 140 },
    { title: '结果打分', dataIndex: 'resultStore', width: 140 },
    { title: '创建时间', dataIndex: 'createTime', width: 140 },
    { title: '开始时间', dataIndex: 'startTime', width: 140 },
    { title: '结束时间', dataIndex: 'endTime', width: 140 },
    {
      title: '操作',
      dataIndex: 'status',
      align: 'center',
      width: 150,
      render: (val, record: any) => (
        <Space size="small">
          {(prewEvaluationTask || userInfoAll.id === record.createBy) && (
            <Tooltip title="详情">
              <Button
                type="link"
                onClick={() => {
                  setOpenIndicatorRag(true);
                  setRecord(record);
                }}
                icon={<RadarChartOutlined />}
              />
            </Tooltip>
          )}
          {(record.status === '2' || record.status === '3') && (
            <Tooltip title="查看评测历史">
              <Button
                type="link"
                onClick={() => {
                  setOpenEvaluationTaskHistory(true);
                  setRecord(record);
                }}
                icon={<LayoutOutlined />}
              />
            </Tooltip>
          )}
          {(startEvaluationTask || userInfoAll.id === record.createBy) && record.status === '0' && (
            <Button type="link" onClick={async () => {
              onBeginEvaluationApi(record);
            }}>开始</Button>
          )}
          {(startEvaluationTask || userInfoAll.id === record.createBy) && record.status !== '0' && record.status !== '1' && (
            <Tooltip title="重新评测">
              <Button type="link" icon={<RedoOutlined />} onClick={() => { onBeginEvaluationApi(record) }} />
            </Tooltip>
          )}
          {(deleteEvaluationTask || userInfoAll.id === record.createBy) && (
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                Modal.confirm({
                  title: '提示',
                  content: `确定删除【${record.taskName}】任务吗？`,
                  okType: 'danger',
                  onOk: async () => {
                    const res: any = await deleteEvaluationApi(record.taskId);
                    if (res.code === 200) {
                      message.success('删除成功');
                      init();
                    }
                  }
                });
              }}
            />
          )}
        </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 [openCreateTaskMode, setOpenCreateTaskMode] = 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>创建和管理 RAG 模型评测任务</p>
        </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 }}>
          <p style={{ margin: 0, fontWeight: 600 }}>任务管理</p>
          <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="taskId"
          loading={loading}
          pagination={paginationConfig}
          scroll={{ x: 'max-content' }}
        />
      </div>

      {/* 弹窗组件 */}
      <CreateTaskMode openCreateTaskMode={openCreateTaskMode} onCancel={() => { setOpenCreateTaskMode(false); init(); }} />
      <IndicatorRag open={openIndicatorRag} record={record} onCancel={() => { setOpenIndicatorRag(false); }} />
      <EvaluationTaskHistory open={openEvaluationTaskHistory} record={record} onClose={() => { setOpenEvaluationTaskHistory(false); }} />
    </div>
  );
};

export default EvaluationTaskList;
