import React, { useState } from 'react';
import { Button, Input, message, Modal, Typography } from 'antd';
import { PlayCircleOutlined } from '@ant-design/icons';
import { customRequest } from 'helpers/http';

const { Text } = Typography;

interface RunWorkflowModalProps {
  workflowId: string;
  workflowName: string;
  onSuccess?: (instanceId: string) => void;
}

export function RunWorkflowModal({
  workflowId,
  workflowName,
  onSuccess,
}: RunWorkflowModalProps) {
  const [open, setOpen] = useState(false);
  const [contextJson, setContextJson] = useState('{}');
  const [loading, setLoading] = useState(false);
  const [jsonError, setJsonError] = useState<string | null>(null);

  const handleOpen = () => {
    setOpen(true);
    setContextJson('{}');
    setJsonError(null);
  };

  const handleContextChange = (value: string) => {
    setContextJson(value);
    try {
      JSON.parse(value);
      setJsonError(null);
    } catch (e: any) {
      setJsonError(e.message);
    }
  };

  const handleExecute = async () => {
    let context: Record<string, any>;
    try {
      context = JSON.parse(contextJson);
    } catch {
      message.error('Invalid JSON input');
      return;
    }

    setLoading(true);
    try {
      const res = await customRequest<{ instanceId: string }>(
        `workflow/${workflowId}/execute`,
        'POST',
        { context },
      );
      message.success('Workflow execution started');
      setOpen(false);
      onSuccess?.(res.instanceId);
    } catch (e: any) {
      message.error(e?.message || 'Failed to execute workflow');
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <Button type="primary" icon={<PlayCircleOutlined />} onClick={handleOpen}>
        Run
      </Button>
      <Modal
        title={`Run: ${workflowName}`}
        open={open}
        onCancel={() => setOpen(false)}
        onOk={handleExecute}
        confirmLoading={loading}
        okText="Execute"
        okButtonProps={{ disabled: !!jsonError }}
      >
        <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
          Input context (JSON). This data will be available to all nodes.
        </Text>
        <Input.TextArea
          rows={8}
          value={contextJson}
          onChange={(e) => handleContextChange(e.target.value)}
          style={{ fontFamily: 'monospace', fontSize: 13 }}
          status={jsonError ? 'error' : undefined}
        />
        {jsonError && (
          <Text
            type="danger"
            style={{ fontSize: 12, marginTop: 4, display: 'block' }}
          >
            {jsonError}
          </Text>
        )}
      </Modal>
    </>
  );
}
