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

interface NodeInstance {
  id: string;
  nodeTypeId: string;
  name: string;
  description: string | null;
  config: Record<string, any>;
  isEnabled: boolean;
}

export default function NodeInstanceEditPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [nodeTypes, setNodeTypes] = useState<WorkflowNodeType[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [record, setRecord] = useState<NodeInstance | null>(null);

  const fetchData = useCallback(async () => {
    try {
      const [ntRes, recordRes] = await Promise.all([
        customRequest<WorkflowNodeType[]>('workflow-node-types', 'GET'),
        customRequest<NodeInstance>(
          `workflowNodeInstance/findUnique/${id}`,
          'POST',
          {
            id: true,
            nodeTypeId: true,
            name: true,
            description: true,
            config: true,
            isEnabled: true,
            nodeType: {
              select: { label: true, category: true, configSchema: true },
            },
          },
        ),
      ]);
      setNodeTypes(ntRes);
      setRecord(recordRes);
      form.setFieldsValue({
        nodeTypeId: String(recordRes.nodeTypeId),
        name: recordRes.name,
        description: recordRes.description ?? '',
        isEnabled: recordRes.isEnabled,
        config:
          typeof recordRes.config === 'string'
            ? JSON.parse(recordRes.config)
            : recordRes.config,
      });
    } catch (e: any) {
      message.error(e?.message ?? 'Failed to load');
    } finally {
      setLoading(false);
    }
  }, [id, form]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

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

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

  return (
    <NodeInstanceForm
      form={form}
      nodeTypes={nodeTypes}
      title={record?.name || 'Edit Node Instance'}
      submitText="Save"
      submitting={submitting}
      disableNodeType
      onSubmit={handleSubmit}
      onBack={() => navigate('/admin/workflow/node-instances')}
    />
  );
}
