import React, { useMemo, useState } from 'react';
import {
  Button,
  Card,
  Form,
  Input,
  Modal,
  Select,
  Switch,
  Typography,
} from 'antd';
import { ArrowLeftOutlined, RobotOutlined } from '@ant-design/icons';
import type { FormInstance } from 'antd';
import { DynamicConfigForm } from './DynamicConfigForm';
import {
  CreateNodeInstanceModal,
  type AiGenerateResult,
} from './CreateNodeInstanceModal';
import type { WorkflowNodeType } from '../../types';

const { Title } = Typography;
const isDev = import.meta.env.DEV;

interface NodeInstanceFormProps {
  form: FormInstance;
  nodeTypes: WorkflowNodeType[];
  title: string;
  submitText: string;
  submitting: boolean;
  disableNodeType?: boolean;
  onSubmit: () => void;
  onBack: () => void;
}

export function NodeInstanceForm({
  form,
  nodeTypes,
  title,
  submitText,
  submitting,
  disableNodeType,
  onSubmit,
  onBack,
}: NodeInstanceFormProps) {
  const [aiModalOpen, setAiModalOpen] = useState(false);

  const selectedNodeTypeId = Form.useWatch('nodeTypeId', form);

  const selectedSchema = useMemo(() => {
    if (!selectedNodeTypeId) return null;
    const nt = nodeTypes.find(
      (t) => String(t.id) === String(selectedNodeTypeId),
    );
    return nt?.configSchema ?? null;
  }, [selectedNodeTypeId, nodeTypes]);

  function handleAiApply(data: AiGenerateResult) {
    const currentName = form.getFieldValue('name');
    const currentDesc = form.getFieldValue('description');
    const currentConfig = form.getFieldValue('config');
    const hasExistingValues = currentName || currentDesc || currentConfig;

    if (hasExistingValues) {
      Modal.confirm({
        title: '覆盖确认',
        content: 'AI 生成的内容将覆盖当前填写的内容，是否继续？',
        okText: '确认覆盖',
        cancelText: '取消',
        onOk: () => applyAiData(data),
      });
    } else {
      applyAiData(data);
    }
  }

  function applyAiData(data: AiGenerateResult) {
    form.setFieldsValue({
      nodeTypeId: data.nodeTypeId ? String(data.nodeTypeId) : undefined,
      name: data.name || undefined,
      description: data.description || undefined,
      config: data.config || undefined,
    });
  }

  return (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 64px)' }}>
      <Card style={{ marginBottom: 16 }}>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Button
              type="text"
              icon={<ArrowLeftOutlined />}
              onClick={onBack}
            ></Button>
            <Title level={4} style={{ margin: 0 }}>
              {title}
            </Title>
          </div>
          {isDev && (
            <Button
              type="primary"
              icon={<RobotOutlined />}
              onClick={() => setAiModalOpen(true)}
            >
              AI 自动生成
            </Button>
          )}
        </div>
      </Card>

      <Card style={{ padding: '24px 32px' }}>
        <Form form={form} layout="vertical" style={{ maxWidth: 600 }}>
          <Form.Item
            name="nodeTypeId"
            label="Node Type"
            rules={[{ required: true, message: 'Please select a node type' }]}
          >
            <Select
              placeholder="Select node type"
              disabled={disableNodeType}
              showSearch
              optionFilterProp="label"
              options={nodeTypes.map((nt) => ({
                label: `${nt.label} (${nt.category})`,
                value: String(nt.id),
              }))}
            />
          </Form.Item>

          <Form.Item
            name="name"
            label="Instance Name"
            rules={[{ required: true, message: 'Please enter a name' }]}
          >
            <Input placeholder="e.g. Send Slack to #general" />
          </Form.Item>

          <Form.Item name="description" label="Description">
            <Input.TextArea rows={2} placeholder="Optional description" />
          </Form.Item>

          <Form.Item name="isEnabled" label="Enabled" valuePropName="checked">
            <Switch />
          </Form.Item>

          {selectedSchema && (
            <>
              <Title level={5} style={{ color: '#595959' }}>
                Configuration
              </Title>
              <DynamicConfigForm schema={selectedSchema} />
            </>
          )}

          <div style={{ marginTop: 24, display: 'flex', gap: 12 }}>
            <Button onClick={onBack}>Cancel</Button>
            <Button type="primary" loading={submitting} onClick={onSubmit}>
              {submitText}
            </Button>
          </div>
        </Form>
      </Card>

      <CreateNodeInstanceModal
        open={aiModalOpen}
        nodeTypes={nodeTypes}
        onClose={() => setAiModalOpen(false)}
        onApply={handleAiApply}
      />
    </div>
  );
}
