import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { Badge, Steps, theme, Typography, message } from 'antd';
import React, { useRef } from 'react';
import { useIntl } from '@umijs/max';
import { useTypewriter } from '@/hooks/useTypewriter';
import { queryWorkflowList, controlWorkflow } from '@/services/workflow';
import { WorkflowStatus, WorkflowTask } from './data';

const { Text } = Typography;

/** 
 * 流式日志组件 
 */
const LogTerminal: React.FC<{ logs: string }> = ({ logs }) => {
    const { token } = theme.useToken();
    const intl = useIntl();
    const displayed = useTypewriter(logs, 10);

    return (
        <div
            style={{
                background: '#1e1e1e',
                color: '#d4d4d4',
                padding: token.paddingSM,
                borderRadius: token.borderRadius,
                fontFamily: 'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',
                fontSize: '12px',
                lineHeight: '1.5',
                marginTop: token.marginSM,
                border: `1px solid ${token.colorBorder}`,
                minHeight: '60px',
                maxHeight: '200px',
                overflowY: 'auto',
            }}
        >
            <div style={{ color: token.colorSuccess, marginBottom: 4 }}>
                $ [SYSTEM LOG] {new Date().toLocaleTimeString()}
            </div>
            {displayed || intl.formatMessage({ id: 'pages.workflow.logs.waiting' })}
            <span
                style={{
                    display: 'inline-block',
                    width: '8px',
                    height: '15px',
                    background: token.colorSuccess,
                    marginLeft: 4,
                    verticalAlign: 'middle',
                    animation: 'blink 1s step-end infinite',
                }}
            />
            <style>{`
        @keyframes blink {
          from, to { opacity: 1; }
          50% { opacity: 0; }
        }
      `}</style>
        </div>
    );
};

const WorkflowOrchestrator: React.FC = () => {
    const { token } = theme.useToken();
    const intl = useIntl();
    const actionRef = useRef<ActionType>();

    const statusMap: Record<WorkflowStatus, { text: string; status: 'default' | 'processing' | 'success' | 'error' | 'warning' }> = {
        thinking: { text: intl.formatMessage({ id: 'pages.workflow.status.thinking' }), status: 'default' },
        executing: { text: intl.formatMessage({ id: 'pages.workflow.status.executing' }), status: 'processing' },
        success: { text: intl.formatMessage({ id: 'pages.workflow.status.success' }), status: 'success' },
        failed: { text: intl.formatMessage({ id: 'pages.workflow.status.failed' }), status: 'error' },
        retrying: { text: intl.formatMessage({ id: 'pages.workflow.status.retrying' }), status: 'warning' },
    };

    const handleControl = async (id: string, action: 'stop' | 'retry' | 'resume') => {
        try {
            await controlWorkflow(id, action);
            message.success(intl.formatMessage({ id: 'common.success.save.mock' }));
            actionRef.current?.reload();
        } catch (e) {
            message.error(intl.formatMessage({ id: 'common.error.update' }));
        }
    };

    const columns: ProColumns<WorkflowTask>[] = [
        {
            title: intl.formatMessage({ id: 'pages.workflow.columns.name' }),
            dataIndex: 'name',
            copyable: true,
            ellipsis: true,
            width: 250,
        },
        {
            title: intl.formatMessage({ id: 'pages.workflow.columns.status' }),
            dataIndex: 'status',
            width: 120,
            valueEnum: statusMap,
            render: (_, record) => {
                const config = statusMap[record.status];
                return <Badge status={config.status} text={config.text} />;
            },
        },
        {
            title: intl.formatMessage({ id: 'pages.workflow.columns.progress' }),
            dataIndex: 'progress',
            valueType: 'progress',
            width: 200,
        },
        {
            title: intl.formatMessage({ id: 'pages.workflow.columns.startTime' }),
            dataIndex: 'createTime',
            valueType: 'dateTime',
            sorter: true,
            hideInSearch: true,
        },
        {
            title: intl.formatMessage({ id: 'pages.workflow.columns.action' }),
            valueType: 'option',
            width: 120,
            render: (_, record) => [
                <a key="view" onClick={() => { }}>{intl.formatMessage({ id: 'pages.workflow.action.view' })}</a>,
                <a
                    key="stop"
                    style={{ color: token.colorError }}
                    onClick={() => handleControl(record.id, 'stop')}
                >
                    {intl.formatMessage({ id: 'pages.workflow.action.stop' })}
                </a>,
            ],
        },
    ];

    return (
        <ProTable<WorkflowTask>
            headerTitle={intl.formatMessage({ id: 'pages.workflow.title' })}
            actionRef={actionRef}
            rowKey="id"
            search={{
                layout: 'vertical',
                defaultCollapsed: false,
            }}
            request={async (params) => {
                const res = await queryWorkflowList(params);
                return {
                    data: res.data,
                    success: true,
                    total: res.total,
                };
            }}
            polling={3000} // 每 3 秒自动轮询更新状态
            columns={columns}
            pagination={{
                pageSize: 10,
            }}
            expandable={{
                expandedRowRender: (record) => (
                    <div style={{ padding: `${token.padding}px ${token.paddingLG}px` }}>
                        <Text strong style={{ display: 'block', marginBottom: token.marginSM }}>
                            {intl.formatMessage({ id: 'pages.workflow.steps.title' })}
                        </Text>
                        <Steps
                            size="small"
                            current={record.steps.findIndex((s) => s.id === record.currentStepId)}
                            items={record.steps.map((step) => ({
                                title: step.agentName,
                                subTitle: step.startTime,
                                description: step.status === 'executing' ? intl.formatMessage({ id: 'pages.workflow.status.executing' }) : '',
                                status: step.status as any,
                            }))}
                        />
                        <LogTerminal
                            logs={record.steps.find((s) => s.id === record.currentStepId)?.logs || ''}
                        />
                    </div>
                ),
            }}
            style={{
                background: token.colorBgContainer,
            }}
        />
    );
};

export default WorkflowOrchestrator;
