import React, { useState, useEffect } from 'react';
import { Card, Table, Tag, Space, Empty } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { getWorkflowInstances } from './service';
import { WorkflowTemplateWithInstances } from './types';
import { Page } from '@/types/base';
// DetailModal 暂时移除，因为数据结构不匹配 (需要 WorkflowHistoricalInstance 而不是 WorkflowTemplateWithInstances)
import HistoryModal from './components/HistoryModal';

const WorkflowInstanceList: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<Page<WorkflowTemplateWithInstances> | null>(null);
    const [query, setQuery] = useState({
        current: 1,
        pageSize: 10,
    });
    // 移除未使用的详情弹窗相关状态
    // const [detailVisible, setDetailVisible] = useState(false);
    // const [selectedInstance, setSelectedInstance] = useState<WorkflowTemplateWithInstances>();
    const [historyVisible, setHistoryVisible] = useState(false);
    const [selectedWorkflowDefinitionId, setSelectedWorkflowDefinitionId] = useState<number>();

    const loadData = async (params: any) => {
        setLoading(true);
        try {
            const result = await getWorkflowInstances(params);
            setData(result);
        } catch (error) {
            console.error('加载流程实例失败:', error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        loadData(query);
    }, [query]);

    const handleViewHistory = (record: WorkflowTemplateWithInstances) => {
        setSelectedWorkflowDefinitionId(record.id);
        setHistoryVisible(true);
    };

    const columns: ColumnsType<WorkflowTemplateWithInstances> = [
        {
            title: '流程名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '业务标识',
            dataIndex: 'businessKey',
            key: 'businessKey',
        },
        {
            title: '最后执行时间',
            dataIndex: 'lastExecutionTime',
            key: 'lastExecutionTime',
            render: (time: string) => time || '暂无'
        },
        {
            title: '最后执行状态',
            dataIndex: 'lastExecutionStatus',
            key: 'lastExecutionStatus',
            render: (status: string) => {
                if (!status) return '暂无';
                const statusMap: Record<string, { color: string; text: string }> = {
                    TERMINATED: { color: 'warning', text: '已终止' },
                    COMPLETED: { color: 'success', text: '已完成' },
                    RUNNING: { color: 'processing', text: '运行中' },
                    FAILED: { color: 'error', text: '失败' },
                    NOT_STARTED: { color: 'default', text: '未执行' }
                };
                const statusInfo = statusMap[status] || { color: 'default', text: status };
                return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
            },
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 200,
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => handleViewHistory(record)}>历史执行</a>
                    {record?.lastExecutionStatus === 'RUNNING' && (
                        <a onClick={() => console.log('终止流程', record)}>终止流程</a>
                    )}
                </Space>
            ),
        },
    ];

    const handleTableChange = (pagination: any) => {
        setQuery({
            ...query,
            current: pagination.current,
            pageSize: pagination.pageSize,
        });
    };

    return (
        <Card title="流程实例">
            <Table
                columns={columns}
                dataSource={data?.content || []}
                loading={loading}
                rowKey="id"
                scroll={{ x: 1200 }}
                locale={{
                    emptyText: <Empty description="暂无数据" />
                }}
                pagination={{
                    current: query.current,
                    pageSize: query.pageSize,
                    total: data?.totalElements || 0,
                    showSizeChanger: true,
                    showQuickJumper: true,
                }}
                onChange={handleTableChange}
            />
            {/* DetailModal 暂时移除，因为数据结构不匹配 */}
            {/* <DetailModal
                visible={detailVisible}
                onCancel={() => setDetailVisible(false)}
                instanceData={selectedInstance}
            /> */}
            <HistoryModal
                visible={historyVisible}
                onCancel={() => setHistoryVisible(false)}
                workflowDefinitionId={selectedWorkflowDefinitionId}
            />
        </Card>
    );
};

export default WorkflowInstanceList;