import { useEffect, useState } from 'react';
import { Button, Card, Drawer, Form, Input, Select, Space, Switch, Tooltip, Typography, App as AntApp } from 'antd';
import type { Workflow, WorkflowGraph, WorkflowNode, WorkflowNodeType } from '../../../api';
import { WorkflowAPI } from '../../../api';
import { NODE_TYPE_LABEL, SAMPLE_GRAPH } from '../constants';

const { Text, Paragraph } = Typography;

export default function WorkflowEditorDrawer(props: {
  open: boolean;
  workflow: Workflow;
  onClose: () => void;
  onSaved: () => void;
}) {
  const { open, workflow, onClose, onSaved } = props;
  const { message } = AntApp.useApp();
  const [form] = Form.useForm();
  const [graphText, setGraphText] = useState(JSON.stringify(workflow.graph, null, 2));
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    form.setFieldsValue({
      name: workflow.name,
      description: workflow.description,
      scheduleCron: workflow.scheduleCron,
      scheduleEnabled: workflow.scheduleEnabled,
      enabled: workflow.enabled
    });
    setGraphText(JSON.stringify(workflow.graph, null, 2));
  }, [workflow]);

  const onSave = async () => {
    const values = await form.validateFields();
    let graph: WorkflowGraph;
    try {
      graph = JSON.parse(graphText);
    } catch (e: any) {
      message.error('Graph JSON 解析失败：' + e.message);
      return;
    }
    if (!graph.entry || !Array.isArray(graph.nodes)) {
      message.error('Graph 必须包含 entry + nodes 数组');
      return;
    }
    setSaving(true);
    try {
      const payload = { ...values, graph };
      if (workflow.id) {
        await WorkflowAPI.update(workflow.id, payload);
      } else {
        await WorkflowAPI.create(payload);
      }
      message.success('已保存');
      onSaved();
    } catch (e: any) {
      message.error('保存失败：' + (e?.message ?? e));
    } finally {
      setSaving(false);
    }
  };

  return (
    <Drawer
      title={workflow.id ? `编辑「${workflow.name}」` : '新建工作流'}
      width={840}
      open={open}
      onClose={onClose}
      styles={{ body: { background: '#fcfcfd' }, header: { background: '#fff', borderBottom: '1px solid var(--color-border)' } }}
      extra={
        <Button type="primary" loading={saving} onClick={onSave} style={{ borderRadius: 10 }}>
          保存
        </Button>
      }
    >
      <Form form={form} layout="vertical">
        <Form.Item label="名称" name="name" rules={[{ required: true, message: '必填' }]}>
          <Input />
        </Form.Item>
        <Form.Item label="描述" name="description">
          <Input.TextArea rows={2} />
        </Form.Item>
        <Space size="large" style={{ marginBottom: 12 }}>
          <Form.Item name="enabled" valuePropName="checked" noStyle>
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
          <Form.Item name="scheduleEnabled" valuePropName="checked" noStyle>
            <Switch checkedChildren="定时开" unCheckedChildren="定时关" />
          </Form.Item>
        </Space>
        <Form.Item
          label={
            <Space>
              <span>Cron 表达式</span>
              <Text type="secondary" style={{ fontSize: 12 }}>
                5 段：分 时 日 月 周，例如 \"*/30 * * * *\"
              </Text>
            </Space>
          }
          name="scheduleCron"
        >
          <Input placeholder="例如 0 8 * * 1-5（工作日早 8 点）" />
        </Form.Item>
      </Form>

      <NodeQuickAdd
        onAdd={(node) => {
          try {
            const g: WorkflowGraph = JSON.parse(graphText);
            g.nodes = [...(g.nodes || []), node];
            if (!g.entry) g.entry = node.id;
            setGraphText(JSON.stringify(g, null, 2));
          } catch {
            message.error('Graph JSON 不合法，无法追加');
          }
        }}
      />

      <Card
        size="small"
        title={<Text strong>Graph JSON（节点列表）</Text>}
        style={{ marginTop: 12, borderRadius: 16, boxShadow: 'var(--shadow-xs)' }}
        extra={
          <Tooltip title="还原为示例">
            <Button size="small" onClick={() => setGraphText(JSON.stringify(SAMPLE_GRAPH, null, 2))} style={{ borderRadius: 8 }}>
              示例
            </Button>
          </Tooltip>
        }
      >
        <Input.TextArea
          rows={20}
          value={graphText}
          onChange={(e) => setGraphText(e.target.value)}
          style={{ fontFamily: 'ui-monospace, monospace', fontSize: 12 }}
        />
        <Paragraph type="secondary" style={{ fontSize: 12, marginTop: 8 }}>
          支持模板 <code>{'{{input.x}} {{vars.x}} {{steps.<nodeId>.output...}}'}</code>。
          <br />
          节点类型：agent / skill / http / transform / branch；branch 节点用 <code>condition</code>（返回 bool 的 JS 片段），引擎按 next/elseNext 走。
        </Paragraph>
      </Card>
    </Drawer>
  );
}

function NodeQuickAdd({ onAdd }: { onAdd: (n: WorkflowNode) => void }) {
  const [type, setType] = useState<WorkflowNodeType>('agent');
  const [id, setId] = useState('');
  return (
    <Card size="small" title="快速追加节点" style={{ marginTop: 12, borderRadius: 16, boxShadow: 'var(--shadow-xs)' }}>
      <Space wrap>
        <Select
          value={type}
          style={{ width: 140 }}
          onChange={(v) => setType(v as WorkflowNodeType)}
          options={Object.entries(NODE_TYPE_LABEL).map(([k, label]) => ({ value: k, label }))}
        />
        <Input placeholder="节点 id（如 step1）" value={id} onChange={(e) => setId(e.target.value)} style={{ width: 200 }} />
        <Button
          type="primary"
          disabled={!id.trim()}
          style={{ borderRadius: 10 }}
          onClick={() => {
            const base: WorkflowNode = { id: id.trim(), type, name: NODE_TYPE_LABEL[type], config: defaultConfig(type), next: '' };
            if (type === 'branch') base.elseNext = '';
            onAdd(base);
            setId('');
          }}
        >
          追加
        </Button>
      </Space>
    </Card>
  );
}

function defaultConfig(type: WorkflowNodeType): Record<string, any> {
  switch (type) {
    case 'agent':
      return { agentId: '', prompt: '请帮我处理：{{input.text}}' };
    case 'skill':
      return { skillId: '', args: {} };
    case 'http':
      return { method: 'GET', url: 'https://example.com/api', headers: {}, body: null };
    case 'transform':
      return { code: 'return { value: input.text };' };
    case 'branch':
      return { condition: 'steps.prev?.output?.value === true' };
  }
}

