import { useEffect, useState } from 'react';
import { Button, Card, Drawer, Form, Input, Modal, Space, Table, Tabs, Tag, Typography, App as AntApp } from 'antd';
import type { Workflow, WorkflowRun, WorkflowRunDetail } from '../../../api';
import { WorkflowAPI, streamWorkflowRun } from '../../../api';
import { STATUS_COLOR } from '../constants';

const { Text, Paragraph } = Typography;

export default function RunsDrawer(props: { open: boolean; workflow: Workflow; onClose: () => void }) {
  const { open, workflow, onClose } = props;
  const { message } = AntApp.useApp();
  const [tab, setTab] = useState('run');
  const [runs, setRuns] = useState<WorkflowRun[]>([]);
  const [detail, setDetail] = useState<WorkflowRunDetail | null>(null);
  const [streaming, setStreaming] = useState(false);
  const [steps, setSteps] = useState<any[]>([]);
  const [finalRun, setFinalRun] = useState<any>(null);
  const [inputJson, setInputJson] = useState('{}');

  const loadRuns = async () => {
    try {
      const data = await WorkflowAPI.listRuns(workflow.id, 30);
      setRuns(data);
    } catch (e: any) {
      message.error('加载历史失败：' + (e?.message ?? e));
    }
  };

  useEffect(() => {
    if (open) loadRuns();
  }, [open]);

  const onRunStream = () => {
    let input: any = undefined;
    if (inputJson.trim()) {
      try {
        input = JSON.parse(inputJson);
      } catch {
        message.error('input JSON 不合法');
        return;
      }
    }
    setSteps([]);
    setFinalRun(null);
    setStreaming(true);
    streamWorkflowRun(workflow.id, input, {
      onStepStart: (d) => setSteps((s) => [...s, { ...d, status: 'running' }]),
      onStepFinish: (d) => {
        setSteps((s) => {
          const idx = [...s].reverse().findIndex((x) => x.nodeId === d.nodeId && x.status === 'running');
          if (idx === -1) return [...s, d];
          const realIdx = s.length - 1 - idx;
          const cp = [...s];
          cp[realIdx] = d;
          return cp;
        });
      },
      onRunFinish: (d) => {
        setStreaming(false);
        setFinalRun(d);
        loadRuns();
      },
      onError: (msg) => {
        setStreaming(false);
        message.error(msg);
      }
    });
  };

  const showDetail = async (runId: string) => {
    try {
      const d = await WorkflowAPI.getRun(runId);
      setDetail(d);
    } catch (e: any) {
      message.error('加载详情失败：' + (e?.message ?? e));
    }
  };

  return (
    <Drawer
      title={`运行：${workflow.name}`}
      width={760}
      open={open}
      onClose={() => {
        setDetail(null);
        onClose();
      }}
      styles={{ body: { background: '#fcfcfd' }, header: { background: '#fff', borderBottom: '1px solid var(--color-border)' } }}
    >
      <Tabs
        activeKey={tab}
        onChange={setTab}
        items={[
          {
            key: 'run',
            label: '触发',
            children: (
              <div>
                <Form layout="vertical">
                  <Form.Item label="Input（JSON，会作为 input.* 注入）">
                    <Input.TextArea rows={4} value={inputJson} onChange={(e) => setInputJson(e.target.value)} placeholder='{"text":"hello"}' />
                  </Form.Item>
                </Form>
                <Space style={{ marginBottom: 12 }}>
                  <Button type="primary" loading={streaming} onClick={onRunStream} style={{ borderRadius: 10 }}>
                    ▶ 流式执行
                  </Button>
                  <Button
                    style={{ borderRadius: 10 }}
                    onClick={async () => {
                      try {
                        const r = await WorkflowAPI.run(workflow.id, JSON.parse(inputJson || '{}'));
                        message.success(`已触发 run=${r.runId}`);
                        loadRuns();
                      } catch (e: any) {
                        message.error('触发失败：' + (e?.message ?? e));
                      }
                    }}
                  >
                    同步执行（不看进度）
                  </Button>
                </Space>

                {steps.length > 0 && (
                  <Card size="small" title="实时进度" style={{ marginBottom: 12, borderRadius: 16 }}>
                    {steps.map((s, i) => (
                      <div key={i} style={{ marginBottom: 8 }}>
                        <Space>
                          <Tag color={STATUS_COLOR[s.status] || 'default'}>{s.status}</Tag>
                          <Text strong>{s.nodeId}</Text>
                          <Text type="secondary">{s.nodeType}</Text>
                          {s.durationMs != null && <Text type="secondary">{s.durationMs}ms</Text>}
                        </Space>
                        {s.error && (
                          <Paragraph type="danger" style={{ marginBottom: 0 }}>
                            {s.error}
                          </Paragraph>
                        )}
                        {s.output != null && (
                          <pre style={{ background: '#f5f5f5', padding: 6, borderRadius: 4, fontSize: 12, marginTop: 4, maxHeight: 160, overflow: 'auto' }}>
                            {JSON.stringify(s.output, null, 2)}
                          </pre>
                        )}
                      </div>
                    ))}
                  </Card>
                )}

                {finalRun && (
                  <Card size="small" title="最终结果" style={{ borderRadius: 16 }}>
                    <pre style={{ fontSize: 12, margin: 0 }}>{JSON.stringify(finalRun, null, 2)}</pre>
                  </Card>
                )}
              </div>
            )
          },
          {
            key: 'history',
            label: `历史 (${runs.length})`,
            children: (
              <div>
                <Button size="small" onClick={loadRuns} style={{ marginBottom: 8, borderRadius: 8 }}>
                  刷新
                </Button>
                <Table<WorkflowRun>
                  rowKey="id"
                  size="small"
                  pagination={false}
                  dataSource={runs}
                  columns={[
                    { title: '状态', dataIndex: 'status', render: (s) => <Tag color={STATUS_COLOR[s] || 'default'}>{s}</Tag>, width: 100 },
                    { title: '触发', dataIndex: 'trigger', width: 80 },
                    { title: '开始', dataIndex: 'startedAt', render: (v) => new Date(v).toLocaleString(), width: 180 },
                    { title: '耗时', dataIndex: 'durationMs', render: (v) => `${v} ms`, width: 100 },
                    { title: '', render: (_, r) => <Button size="small" onClick={() => showDetail(r.id)}>详情</Button> }
                  ]}
                />
                {detail && (
                  <Modal title={`Run ${detail.id}`} open onCancel={() => setDetail(null)} onOk={() => setDetail(null)} width={680}>
                    <p>
                      <b>状态：</b>
                      <Tag color={STATUS_COLOR[detail.status] || 'default'}>{detail.status}</Tag>
                      {detail.error && (
                        <Text type="danger" style={{ marginLeft: 8 }}>
                          {detail.error}
                        </Text>
                      )}
                    </p>
                    <p>
                      <b>耗时：</b>
                      {detail.durationMs} ms
                    </p>
                    <p>
                      <b>Input：</b>
                    </p>
                    <pre style={{ background: '#f5f5f5', padding: 8, fontSize: 12 }}>{JSON.stringify(detail.input, null, 2)}</pre>
                    <p>
                      <b>Steps：</b>
                    </p>
                    {detail.steps.map((s) => (
                      <Card size="small" key={s.id} style={{ marginBottom: 8, borderRadius: 14 }}>
                        <Space>
                          <Tag color={STATUS_COLOR[s.status] || 'default'}>{s.status}</Tag>
                          <Text strong>{s.nodeId}</Text>
                          <Text type="secondary">{s.nodeType}</Text>
                          <Text type="secondary">{s.durationMs} ms</Text>
                        </Space>
                        {s.error && <p style={{ color: 'red', marginTop: 4 }}>{s.error}</p>}
                        {s.output != null && (
                          <pre style={{ fontSize: 12, marginTop: 4, maxHeight: 200, overflow: 'auto' }}>{JSON.stringify(s.output, null, 2)}</pre>
                        )}
                      </Card>
                    ))}
                  </Modal>
                )}
              </div>
            )
          }
        ]}
      />
    </Drawer>
  );
}

