async function generate(context) {
  return `/**
 * StandardFormView - Controller-Based Form View Component
 *
 * LOCAL VERSION - Uses local hooks with instance-factory-specific API client
 *
 * Supports both Create and Edit modes with:
 * - Controller-driven form generation
 * - Smart input types (text, number, boolean, relationship selectors)
 * - Auto-generated field detection
 * - Validation and error handling
 * - Lifecycle management (Edit/Evolve tabs)
 * - Foreign key relationship fields
 * - Two-panel layout (form + entity list)
 */

import { useState, useEffect } from 'react';
import { useEntitiesQuery, useModelSchemaQuery, useExecuteOperationMutation, useTransitionStateMutation } from '../../hooks/useApi';
import { isAutoGeneratedField, isFieldRequired, initializeFormData } from '../../utils/field-helpers';
import { RelationshipField } from '../../components/fields/RelationshipField';
import type { View, Entity } from '../../types/api';

type FormMode = 'create' | 'update';
type ActiveTab = 'edit' | 'evolve';

interface StandardFormViewProps {
  view: View;
  spec?: any;  // Full spec for controller access
}

export function FormView({ view, spec }: StandardFormViewProps) {
  // Determine controller and model
  let controllerName: string;
  let modelName: string;

  if (view.controller && spec) {
    // New: Controller-based
    controllerName = view.controller;
    const controller = spec.controllers[view.controller];
    modelName = controller.model;
  } else {
    // Legacy: Model-based
    modelName = view.model as string;
    controllerName = \`\${modelName}Controller\`;
  }

  const [selectedEntity, setSelectedEntity] = useState<Entity | null>(null);
  const [formMode, setFormMode] = useState<FormMode>('create');
  const [activeTab, setActiveTab] = useState<ActiveTab>('edit');
  const [formData, setFormData] = useState<Record<string, any>>({});
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [selectedLifecycleStates, setSelectedLifecycleStates] = useState<Record<string, string>>({});

  // Fetch entities and schema - USES LOCAL HOOKS
  const { data: entities = [], isLoading: entitiesLoading } = useEntitiesQuery(controllerName, modelName);
  const { data: schema } = useModelSchemaQuery(modelName);
  const { mutate: executeOperation, isPending } = useExecuteOperationMutation();
  const { mutate: transitionState, isPending: isTransitioning } = useTransitionStateMutation();

  const attributes = schema?.attributes || {};
  const relationships = schema?.relationships || {};
  const lifecycles = schema?.lifecycles || {};

  // Sync selected entity with updated entities list
  useEffect(() => {
    if (selectedEntity && entities.length > 0) {
      const updatedEntity = entities.find((e) => e.id === selectedEntity.id);
      if (updatedEntity) {
        const oldStates = JSON.stringify(selectedEntity.metadata?.lifecycleStates || {});
        const newStates = JSON.stringify(updatedEntity.metadata?.lifecycleStates || {});

        if (oldStates !== newStates) {
          setSelectedEntity(updatedEntity);
          setSelectedLifecycleStates({ ...(updatedEntity.metadata?.lifecycleStates || {}) });
        }
      }
    }
  }, [entities, selectedEntity?.id]);

  // Initialize form data when schema changes or when switching modes
  useEffect(() => {
    if (selectedEntity && formMode === 'update') {
      setFormData({ ...selectedEntity.data });
      const currentStates = selectedEntity.metadata?.lifecycleStates || {};
      setSelectedLifecycleStates({ ...currentStates });
    } else if (schema?.attributes) {
      setFormData(initializeFormData(schema.attributes, { includeAutoGenerated: false }));
      setSelectedLifecycleStates({});
    }
  }, [selectedEntity, formMode, schema]);

  // Check if field should be shown
  const shouldShowField = (attrName: string, attrDef: any): boolean => {
    const isAuto = isAutoGeneratedField(attrName, attrDef);
    // In create mode, hide auto-generated fields
    if (formMode === 'create' && isAuto) {
      return false;
    }
    // In update mode, show all fields
    return true;
  };

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrors({});

    const operation = formMode === 'create' ? 'create' : 'update';
    const params = formMode === 'update' && selectedEntity
      ? { ...formData, id: selectedEntity.id }
      : formData;

    executeOperation(
      { controllerName, operationName: operation, params },
      {
        onSuccess: () => {
          if (formMode === 'create' && schema?.attributes) {
            setFormData(initializeFormData(schema.attributes, { includeAutoGenerated: false }));
          }
          setFormMode('create');
          setSelectedEntity(null);
        },
        onError: (error: any) => {
          setErrors({ _form: error.message || 'Operation failed' });
        }
      }
    );
  };

  // Handle entity selection for editing
  const handleEntitySelect = (entity: Entity) => {
    setSelectedEntity(entity);
    setFormMode('update');
    setActiveTab('edit');
  };

  // Handle lifecycle state transition
  const handleLifecycleTransition = (lifecycleName: string, toState: string) => {
    if (!selectedEntity) return;

    transitionState(
      { modelName, entityId: selectedEntity.id, toState, lifecycleName },
      {
        onSuccess: () => {
          setSelectedLifecycleStates((prev) => ({ ...prev, [lifecycleName]: toState }));
        },
        onError: (error: any) => {
          setErrors({ _lifecycle: error.message || 'Transition failed' });
        }
      }
    );
  };

  // Render field input
  const renderFieldInput = (attrName: string, attrDef: any) => {
    const value = formData[attrName] ?? '';
    const isRequired = isFieldRequired(attrDef);

    const handleChange = (newValue: any) => {
      setFormData((prev) => ({ ...prev, [attrName]: newValue }));
    };

    // Boolean field
    if (attrDef.type === 'Boolean') {
      return (
        <input
          type="checkbox"
          checked={!!value}
          onChange={(e) => handleChange(e.target.checked)}
          className="h-4 w-4 rounded border-gray-300"
        />
      );
    }

    // Number field
    if (attrDef.type === 'Integer' || attrDef.type === 'Float' || attrDef.type === 'Decimal') {
      return (
        <input
          type="number"
          value={value}
          onChange={(e) => handleChange(e.target.value ? Number(e.target.value) : '')}
          required={isRequired}
          className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
        />
      );
    }

    // Text field (default)
    return (
      <input
        type="text"
        value={value}
        onChange={(e) => handleChange(e.target.value)}
        required={isRequired}
        className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
      />
    );
  };

  return (
    <div className="flex gap-4 h-full">
      {/* Form Panel */}
      <div className="flex-1 bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <h2 className="text-2xl font-bold mb-4 text-gray-800 dark:text-white">
          {formMode === 'create' ? \`Create \${modelName}\` : \`Edit \${modelName}\`}
        </h2>

        {/* Tabs for Edit/Evolve modes */}
        {formMode === 'update' && Object.keys(lifecycles).length > 0 && (
          <div className="flex gap-2 mb-4 border-b border-gray-200">
            <button
              onClick={() => setActiveTab('edit')}
              className={\`px-4 py-2 font-medium \${activeTab === 'edit' ? 'border-b-2 border-blue-500 text-blue-600' : 'text-gray-500'}\`}
            >
              Edit Data
            </button>
            <button
              onClick={() => setActiveTab('evolve')}
              className={\`px-4 py-2 font-medium \${activeTab === 'evolve' ? 'border-b-2 border-blue-500 text-blue-600' : 'text-gray-500'}\`}
            >
              Lifecycle
            </button>
          </div>
        )}

        {activeTab === 'edit' ? (
          <form onSubmit={handleSubmit} className="space-y-4">
            {errors._form && (
              <div className="p-3 bg-red-100 text-red-700 rounded-md">{errors._form}</div>
            )}

            {/* Attributes */}
            {Object.entries(attributes).map(([attrName, attrDef]: [string, any]) => {
              if (!shouldShowField(attrName, attrDef)) return null;

              return (
                <div key={attrName}>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {attrName}
                    {isFieldRequired(attrDef) && <span className="text-red-500">*</span>}
                  </label>
                  {renderFieldInput(attrName, attrDef)}
                </div>
              );
            })}

            {/* Relationships */}
            {Object.entries(relationships).map(([relName, relDef]: [string, any]) => (
              <RelationshipField
                key={relName}
                name={relName}
                relationship={relDef}
                value={formData[relName]}
                onChange={(value) => setFormData((prev) => ({ ...prev, [relName]: value }))}
              />
            ))}

            <div className="flex gap-2 pt-4">
              <button
                type="submit"
                disabled={isPending}
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
              >
                {isPending ? 'Saving...' : formMode === 'create' ? 'Create' : 'Update'}
              </button>
              {formMode === 'update' && (
                <button
                  type="button"
                  onClick={() => {
                    setFormMode('create');
                    setSelectedEntity(null);
                    if (schema?.attributes) {
                      setFormData(initializeFormData(schema.attributes, { includeAutoGenerated: false }));
                    }
                  }}
                  className="px-4 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600"
                >
                  Cancel
                </button>
              )}
            </div>
          </form>
        ) : (
          /* Lifecycle Tab */
          <div className="space-y-4">
            {errors._lifecycle && (
              <div className="p-3 bg-red-100 text-red-700 rounded-md">{errors._lifecycle}</div>
            )}

            {Object.entries(lifecycles).map(([lifecycleName, lifecycle]: [string, any]) => {
              const currentState = selectedLifecycleStates[lifecycleName] || lifecycle.initial;

              return (
                <div key={lifecycleName} className="border border-gray-200 rounded-lg p-4">
                  <h3 className="font-semibold text-lg mb-2">{lifecycleName}</h3>
                  <p className="text-sm text-gray-600 mb-3">Current: {currentState}</p>

                  <div className="flex flex-wrap gap-2">
                    {Object.keys(lifecycle.states || {}).map((state) => (
                      <button
                        key={state}
                        onClick={() => handleLifecycleTransition(lifecycleName, state)}
                        disabled={isTransitioning || state === currentState}
                        className={\`px-3 py-1 rounded-md \${state === currentState ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'} disabled:opacity-50\`}
                      >
                        {state}
                      </button>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Entity List Panel */}
      <div className="w-80 bg-white dark:bg-gray-800 rounded-lg shadow p-4">
        <h3 className="text-lg font-semibold mb-3 text-gray-800 dark:text-white">
          {modelName} List
        </h3>

        {entitiesLoading ? (
          <p className="text-gray-500">Loading...</p>
        ) : entities.length === 0 ? (
          <p className="text-gray-500 italic">No entities yet</p>
        ) : (
          <div className="space-y-2">
            {entities.map((entity) => (
              <div
                key={entity.id}
                onClick={() => handleEntitySelect(entity)}
                className={\`p-3 rounded-md cursor-pointer \${selectedEntity?.id === entity.id ? 'bg-blue-100 border-blue-500' : 'bg-gray-50 hover:bg-gray-100'} border\`}
              >
                <p className="font-medium text-sm">{entity.id}</p>
                {Object.entries(entity.data).slice(0, 2).map(([key, value]) => (
                  <p key={key} className="text-xs text-gray-600">
                    {key}: {String(value)}
                  </p>
                ))}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

export default FormView;
`;
}
export {
  generate
};
