import React from 'react';
import { Form, Input, InputNumber, Switch, Select } from 'antd';

const { TextArea } = Input;

interface SchemaProperty {
  type: string;
  title?: string;
  description?: string;
  enum?: string[];
  default?: any;
  items?: { type: string; enum?: string[] };
}

interface ConfigSchema {
  type?: string;
  properties?: Record<string, SchemaProperty>;
  required?: string[];
}

interface Props {
  schema: ConfigSchema | null;
  disabled?: boolean;
}

/**
 * Renders Ant Design Form.Items dynamically based on a JSON Schema.
 * Must be used inside a <Form> parent — it does not create its own Form instance.
 * All fields are namespaced under "config" (e.g., Form field name = ["config", "fieldKey"]).
 */
export function DynamicConfigForm({ schema, disabled = false }: Props) {
  if (!schema?.properties) {
    return null;
  }

  const requiredFields = schema.required ?? [];

  return (
    <>
      {Object.entries(schema.properties).map(([key, prop]) => {
        const label = prop.title || key;
        const isRequired = requiredFields.includes(key);

        // Boolean → Switch
        if (prop.type === 'boolean') {
          return (
            <Form.Item
              key={key}
              name={['config', key]}
              label={label}
              tooltip={prop.description}
              valuePropName="checked"
              rules={isRequired ? [{ required: true }] : undefined}
            >
              <Switch disabled={disabled} />
            </Form.Item>
          );
        }

        // Enum → Select
        if (prop.enum) {
          return (
            <Form.Item
              key={key}
              name={['config', key]}
              label={label}
              tooltip={prop.description}
              rules={
                isRequired
                  ? [{ required: true, message: `${label} is required` }]
                  : undefined
              }
            >
              <Select
                disabled={disabled}
                allowClear
                options={prop.enum.map((v) => ({ label: v, value: v }))}
              />
            </Form.Item>
          );
        }

        // Array → Select tags mode
        if (prop.type === 'array') {
          const enumOptions = prop.items?.enum;
          return (
            <Form.Item
              key={key}
              name={['config', key]}
              label={label}
              tooltip={prop.description}
              rules={
                isRequired
                  ? [{ required: true, message: `${label} is required` }]
                  : undefined
              }
            >
              <Select
                mode="tags"
                disabled={disabled}
                allowClear
                options={enumOptions?.map((v) => ({ label: v, value: v }))}
              />
            </Form.Item>
          );
        }

        // Number → InputNumber
        if (prop.type === 'number' || prop.type === 'integer') {
          return (
            <Form.Item
              key={key}
              name={['config', key]}
              label={label}
              tooltip={prop.description}
              rules={
                isRequired
                  ? [{ required: true, message: `${label} is required` }]
                  : undefined
              }
            >
              <InputNumber disabled={disabled} style={{ width: '100%' }} />
            </Form.Item>
          );
        }

        // String (default) → Input or TextArea
        const isLongText =
          prop.description?.includes('multiline') ||
          key.toLowerCase().includes('body') ||
          key.toLowerCase().includes('template');
        return (
          <Form.Item
            key={key}
            name={['config', key]}
            label={label}
            tooltip={prop.description}
            rules={
              isRequired
                ? [{ required: true, message: `${label} is required` }]
                : undefined
            }
          >
            {isLongText ? (
              <TextArea rows={3} disabled={disabled} />
            ) : (
              <Input disabled={disabled} />
            )}
          </Form.Item>
        );
      })}
    </>
  );
}
