import { Form, Input, InputNumber, Select, Switch } from 'antd';
import type { NamePath } from 'antd/es/form/interface';
import { defaultForSchema, resolveSchema, schemaType } from '../api/schema-utils';
import type { JsonSchema } from '../api/types';

interface SchemaFieldsProps {
  schema: JsonSchema;
  prefix: NamePath;
  required?: readonly string[];
}

function fieldName(prefix: NamePath, name: string): NamePath {
  return [...(Array.isArray(prefix) ? prefix : [prefix]), name];
}

export function SchemaFields({ schema, prefix, required = [] }: SchemaFieldsProps) {
  const resolved = resolveSchema(schema);
  const properties = resolved.properties || {};
  return Object.entries(properties).map(([name, propertySchema]) => {
    const property = resolveSchema(propertySchema);
    const type = schemaType(property);
    const label = property.description || name;
    const isRequired = required.includes(name);
    const rules = isRequired ? [{ required: true, message: `请填写${label}` }] : undefined;
    let control = <Input placeholder={property.format === 'uuid' ? 'UUID' : undefined} />;

    if (property.enum?.length) {
      control = <Select options={property.enum.map((value) => ({ label: String(value), value }))} allowClear={!isRequired} />;
    } else if (type === 'boolean') {
      control = <Switch />;
    } else if (type === 'integer' || type === 'number') {
      control = <InputNumber min={property.minimum} max={property.maximum} style={{ width: '100%' }} />;
    } else if (type === 'object' || type === 'array') {
      control = <Input.TextArea autoSize={{ minRows: 3, maxRows: 10 }} placeholder={type === 'array' ? '[]' : '{}'} />;
    } else if (property.format === 'date-time') {
      control = <Input type="datetime-local" />;
    } else if (property.maxLength && property.maxLength > 200) {
      control = <Input.TextArea autoSize={{ minRows: 2, maxRows: 8 }} />;
    }

    return (
      <Form.Item
        key={name}
        name={fieldName(prefix, name)}
        label={label}
        rules={rules}
        valuePropName={type === 'boolean' ? 'checked' : 'value'}
        initialValue={defaultForSchema(property)}
        tooltip={name}
      >
        {control}
      </Form.Item>
    );
  });
}
