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>
  );
}

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

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" }
      }}
    />
  );
}

Element Types

Text Elements

Text elements support various formats and styling options:
{
  type: "text",
  key: "description",
  label: "Description",
  defaultValue: "Enter description here",
  description: "Provide additional details"
}

Document Elements

Handle PDF and ZIP file uploads with automatic processing:
// 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:
{
  type: "csv",
  key: "patientData",
  label: "Patient CSV Data",
  description: "Upload a CSV file with patient information"
}

API Reference

FormProps

elements
FormElement[]
required
Array of form elements defining the structure and validation rules.
onSubmit
function
required
Callback function called when form is successfully submitted.
onSubmit?: (results: Record<string, ReturnData>) => void

FormElement Types

Return Data Types

The onSubmit callback receives a results object with the following data types:
text fields
string
Text inputs return their string values.
single document
DocumentReturn
Single document uploads return an object with id and fileName.
type DocumentReturn = {
  id: string;
  fileName: string;
}
multiple documents
DocumentReturn[]
Multiple document uploads return an array of document objects.
csv files
Record<string, string>[]
CSV uploads return an array of objects, one per row, with column headers as keys.

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

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>
  );
}

Form with Conditional Logic

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>
  );
}

Error Handling

The Form component includes built-in error handling for file uploads and validation:
Upload Failures: If any file uploads fail, the form will display specific error messages and prevent submission until resolved.
Individual File Errors: Each file upload is handled independently. Failed uploads show specific error messages while successful uploads complete normally.
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.

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

// 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