> ## Documentation Index
> Fetch the complete documentation index at: https://docs.samplehc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Form Component

> Advanced form builder with document upload, CSV processing, and validation

## Overview

The Form component is a powerful, declarative form builder that handles various input types including text fields, document uploads, and CSV processing. It automatically manages file uploads, validation, and submission with built-in error handling.

## Basic Usage

<CodeGroup>
  ```tsx Simple Text Form theme={null}
  import { Form } from "@samplehc/ui/components";

  function BasicForm() {
    return (
      <Form 
        elements={[
          {
            type: "text",
            key: "patientName", 
            label: "Patient Name",
            description: "Enter the patient's full name"
          },
          {
            type: "text",
            key: "age",
            label: "Age",
            format: "text"
          }
        ]}
        onSubmit={(results) => {
          console.log("Form data:", results);
          // results = { patientName: "John Doe", age: "35" }
        }}
      />
    );
  }
  ```

  ```tsx Document Upload Form theme={null}
  import { Form } from "@samplehc/ui/components";

  function DocumentForm() {
    return (
      <Form 
        elements={[
          {
            type: "document",
            key: "medicalRecords",
            label: "Medical Records",
            description: "Upload PDF or ZIP files",
            allowMultiple: true
          },
          {
            type: "text",
            key: "notes",
            label: "Additional Notes"
          }
        ]}
        onSubmit={(results) => {
          console.log("Uploaded documents:", results.medicalRecords);
          // results.medicalRecords = [{ id: "doc123", fileName: "record1.pdf" }]
        }}
      />
    );
  }
  ```
</CodeGroup>

## Element Types

### Text Elements

Text elements support various formats and styling options:

<Tabs>
  <Tab title="Basic Text">
    ```tsx theme={null}
    {
      type: "text",
      key: "description",
      label: "Description",
      defaultValue: "Enter description here",
      description: "Provide additional details"
    }
    ```
  </Tab>

  <Tab title="Currency">
    ```tsx theme={null}
    {
      type: "text",
      key: "amount",
      label: "Payment Amount",
      format: "currency",
      prefix: "$",  // Optional custom prefix
      description: "Enter the payment amount in USD"
    }
    ```
  </Tab>

  <Tab title="Percentage">
    ```tsx theme={null}
    {
      type: "text",
      key: "copay",
      label: "Copay Percentage", 
      format: "percentage",
      postfix: "%",  // Optional custom postfix
      description: "Patient's copay percentage"
    }
    ```
  </Tab>
</Tabs>

### Document Elements

Handle PDF and ZIP file uploads with automatic processing:

```tsx theme={null}
// Single document upload
{
  type: "document",
  key: "primaryDocument",
  label: "Primary Document",
  description: "Upload the main document (PDF or ZIP)"
}

// Multiple document upload
{
  type: "document", 
  key: "supportingDocs",
  label: "Supporting Documents",
  allowMultiple: true,
  description: "Upload additional supporting documents"
}
```

### CSV Elements

Process CSV files and extract data:

```tsx theme={null}
{
  type: "csv",
  key: "patientData",
  label: "Patient CSV Data",
  description: "Upload a CSV file with patient information"
}
```

## API Reference

### FormProps

<ParamField path="elements" type="FormElement[]" required>
  Array of form elements defining the structure and validation rules.
</ParamField>

<ParamField path="onSubmit" type="function" required>
  Callback function called when form is successfully submitted.

  ```tsx theme={null}
  onSubmit?: (results: Record<string, ReturnData>) => void
  ```
</ParamField>

### FormElement Types

<Accordion title="BaseFormElement">
  Common properties shared by all form elements:

  <ParamField path="key" type="string" required>
    Unique identifier for the form field. Used as the key in the results object.
  </ParamField>

  <ParamField path="label" type="string" required>
    Display label for the form field.
  </ParamField>

  <ParamField path="description" type="string">
    Optional description text shown below the field.
  </ParamField>
</Accordion>

<Accordion title="TextElement">
  Text input element with formatting options:

  <ParamField path="type" type="'text'" required>
    Element type identifier.
  </ParamField>

  <ParamField path="format" type="'text' | 'currency' | 'percentage'">
    Input format for automatic formatting and validation.
  </ParamField>

  <ParamField path="defaultValue" type="string">
    Default value for the text field.
  </ParamField>

  <ParamField path="prefix" type="string">
    Text prefix displayed before the input (e.g., "\$" for currency).
  </ParamField>

  <ParamField path="postfix" type="string">
    Text postfix displayed after the input (e.g., "%" for percentage).
  </ParamField>
</Accordion>

<Accordion title="DocumentElement">
  Document upload element for PDFs and ZIP files:

  <ParamField path="type" type="'document'" required>
    Element type identifier.
  </ParamField>

  <ParamField path="allowMultiple" type="boolean">
    Allow multiple file uploads. Defaults to false.
  </ParamField>
</Accordion>

<Accordion title="CSVElement">
  CSV file upload element:

  <ParamField path="type" type="'csv'" required>
    Element type identifier.
  </ParamField>
</Accordion>

## Return Data Types

The `onSubmit` callback receives a results object with the following data types:

<ResponseField name="text fields" type="string">
  Text inputs return their string values.
</ResponseField>

<ResponseField name="single document" type="DocumentReturn">
  Single document uploads return an object with `id` and `fileName`.

  ```tsx theme={null}
  type DocumentReturn = {
    id: string;
    fileName: string;
  }
  ```
</ResponseField>

<ResponseField name="multiple documents" type="DocumentReturn[]">
  Multiple document uploads return an array of document objects.
</ResponseField>

<ResponseField name="csv files" type="Record<string, string>[]">
  CSV uploads return an array of objects, one per row, with column headers as keys.
</ResponseField>

## Supported File Types

### Document Upload

* **PDF Files**: `.pdf` documents for medical records, reports, and forms
* **ZIP Archives**: `.zip` files containing multiple documents
* **HTML Files**: `.html` files for web-based documents

### CSV Upload

* **CSV Files**: `.csv` files with tabular data (comma-separated values)
* **Text CSV**: Plain text files with CSV format

## Form Features

### Text Input Formatting

* **Currency**: Automatically formats numbers with decimal places and `$` prefix
* **Percentage**: Automatically formats numbers with `%` postfix
* **Custom Prefixes/Postfixes**: Override default formatting with custom text

### File Upload Features

* **Drag & Drop**: Users can drag files directly onto upload areas
* **Multiple Files**: Support for uploading multiple documents when `allowMultiple` is enabled
* **File Preview**: Shows selected file names with remove buttons
* **Upload Progress**: Real-time upload status with loading indicators
* **Error Handling**: Individual file upload error messages with retry capability

### Form Validation

* Built on `react-hook-form` with `zod` schema validation
* Real-time validation feedback
* Prevents submission until all uploads complete successfully
* Form-wide error handling with specific error messages

## Advanced Examples

### Complex Healthcare Form

<RequestExample>
  ```tsx Complete Example theme={null}
  import { Form } from "@samplehc/ui/components";
  import { useScreenFunctions } from "@samplehc/ui/contexts";
  import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";

  function PatientIntakeForm() {
    const { handleComplete } = useScreenFunctions();

    const formElements = [
      {
        type: "text",
        key: "patientName",
        label: "Patient Full Name",
        description: "As it appears on insurance card"
      },
      {
        type: "text", 
        key: "dateOfBirth",
        label: "Date of Birth",
        description: "MM/DD/YYYY format"
      },
      {
        type: "text",
        key: "copayAmount",
        label: "Copay Amount",
        format: "currency",
        description: "Patient's copay for this visit"
      },
      {
        type: "document",
        key: "insuranceCard",
        label: "Insurance Card",
        description: "Upload front and back of insurance card",
        allowMultiple: true
      },
      {
        type: "document",
        key: "medicalRecords", 
        label: "Previous Medical Records",
        description: "Upload any relevant medical history (PDFs or ZIP files)",
        allowMultiple: true
      },
      {
        type: "csv",
        key: "labResults",
        label: "Lab Results (CSV)",
        description: "Upload lab results in CSV format if available"
      },
      {
        type: "text",
        key: "notes",
        label: "Additional Notes",
        description: "Any additional information about the patient"
      }
    ];

    return (
      <Card className="max-w-4xl mx-auto">
        <CardHeader>
          <CardTitle>Patient Intake Form</CardTitle>
        </CardHeader>
        <CardContent>
          <Form 
            elements={formElements}
            onSubmit={(results) => {
              handleComplete({ result: results });
            }}
          />
        </CardContent>
      </Card>
    );
  }
  ```
</RequestExample>

### Form with Conditional Logic

<RequestExample>
  ```tsx Conditional Form theme={null}
  import { Form } from "@samplehc/ui/components";
  import { useScreenFunctions } from "@samplehc/ui/contexts";

  function ConditionalForm({ hasInsurance }: { hasInsurance: boolean }) {
    const { handleComplete } = useScreenFunctions();

    const baseElements = [
      {
        type: "text",
        key: "patientName", 
        label: "Patient Name"
      }
    ];

    const insuranceElements = hasInsurance ? [
      {
        type: "text",
        key: "insuranceProvider",
        label: "Insurance Provider"
      },
      {
        type: "document",
        key: "insuranceCard",
        label: "Insurance Card"
      }
    ] : [];

    return (
      <div className="space-y-4">      
        <Form 
          elements={[...baseElements, ...insuranceElements]}
          onSubmit={(results) => handleComplete({ result: results })}
        />
      </div>
    );
  }
  ```
</RequestExample>

## Error Handling

The Form component includes built-in error handling for file uploads and validation:

<Warning>
  **Upload Failures**: If any file uploads fail, the form will display specific error messages and prevent submission until resolved.
</Warning>

<Note>
  **Individual File Errors**: Each file upload is handled independently. Failed uploads show specific error messages while successful uploads complete normally.
</Note>

<Tip>
  **Form State Management**: The form manages its own upload state and prevents submission while files are uploading. Use the loading states to provide user feedback.
</Tip>

## Upload Behavior

### Asynchronous File Processing

The Form handles file uploads asynchronously:

1. **Form Submission**: When submitted, all files are uploaded in parallel
2. **Upload Status**: Each file shows individual loading/success/error states
3. **Completion**: `onSubmit` is called only after all uploads complete
4. **Error Handling**: If any upload fails, `onSubmit` receives an empty object `{}`

### Upload Data Flow

```tsx theme={null}
// Successful submission result structure
{
  // Text fields return strings
  patientName: "John Doe",
  
  // Single document returns object
  insuranceCard: { id: "doc123", fileName: "insurance.pdf" },
  
  // Multiple documents return array
  medicalRecords: [
    { id: "doc456", fileName: "record1.pdf" },
    { id: "doc789", fileName: "record2.pdf" }
  ],
  
  // CSV returns parsed data array
  labResults: [
    { "Test": "Glucose", "Value": "95", "Unit": "mg/dL" },
    { "Test": "Cholesterol", "Value": "180", "Unit": "mg/dL" }
  ]
}
```

## Integration with Workflow System

The Form component integrates seamlessly with the SampleHC workflow system:

* **Automatic Upload**: Documents are uploaded to the platform and return permanent IDs
* **Progress Tracking**: Built-in loading states and progress indicators
* **Error Recovery**: Robust error handling with retry mechanisms
