import React, { useEffect, useState } from 'react';
import { Form, Spin, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { customRequest } from 'helpers/http';
import { NodeInstanceForm } from './components/NodeInstanceForm';
import type { WorkflowNodeType } from '../types';

export default function NodeInstanceCreatePage() {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [nodeTypes, setNodeTypes] = useState<WorkflowNodeType[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    customRequest<WorkflowNodeType[]>('workflow-node-types', 'GET')
      .then((res) => {
        setNodeTypes(res);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  // Reset config when nodeType changes
  const selectedNodeTypeId = Form.useWatch('nodeTypeId', form);
  useEffect(() => {
    if (selectedNodeTypeId) {
      form.setFieldValue('config', undefined);
    }
  }, [selectedNodeTypeId, form]);

  async function handleSubmit() {
    try {
      const values = await form.validateFields();
      setSubmitting(true);
      await customRequest('workflowNodeInstance/createOne', 'POST', {
        nodeType: { connect: { id: Number(values.nodeTypeId) } },
        name: values.name,
        description: values.description || null,
        config: JSON.stringify(values.config ?? {}),
        isEnabled: values.isEnabled ?? true,
        creator: '',
      });
      message.success('Created successfully');
      navigate('/admin/workflow/node-instances');
    } catch (e: any) {
      if (e?.errorFields) return;
      message.error(e?.message ?? 'Create failed');
    } finally {
      setSubmitting(false);
    }
  }

  if (loading) {
    return (
      <div
        style={{ display: 'flex', justifyContent: 'center', paddingTop: 120 }}
      >
        <Spin size="large" />
      </div>
    );
  }

  return (
    <Form.Provider>
      <NodeInstanceForm
        form={form}
        nodeTypes={nodeTypes}
        title="Create Node Instance"
        submitText="Create"
        submitting={submitting}
        onSubmit={handleSubmit}
        onBack={() => navigate('/admin/workflow/node-instances')}
      />
    </Form.Provider>
  );
}
