import { Form } from "@samplehc/ui/components";
import { useTaskState, useScreenFunctions } from "@samplehc/ui/lib";
import { Card, CardHeader, CardTitle, CardContent } from "@samplehc/ui/components/ui";

function PatientIntakeForm() {
  const [formData, setFormData] = useTaskState("patientIntake", {});
  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"
    }
  ];

  const handleSubmit = async (results) => {
    // Save to task state
    setFormData(results);
    
    // Complete the workflow step
    await handleComplete({ 
      result: {
        patientIntake: results,
        timestamp: new Date().toISOString()
      }
    });
  };

  return (
    <Card className="max-w-4xl mx-auto">
      <CardHeader>
        <CardTitle>Patient Intake Form</CardTitle>
      </CardHeader>
      <CardContent>
        <Form 
          elements={formElements}
          onSubmit={handleSubmit}
        />
      </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.

Advanced Examples

Complex Healthcare Form

import { Form } from "@samplehc/ui/components";
import { useTaskState, useScreenFunctions } from "@samplehc/ui/lib";
import { Card, CardHeader, CardTitle, CardContent } from "@samplehc/ui/components/ui";

function PatientIntakeForm() {
  const [formData, setFormData] = useTaskState("patientIntake", {});
  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"
    }
  ];

  const handleSubmit = async (results) => {
    // Save to task state
    setFormData(results);
    
    // Complete the workflow step
    await handleComplete({ 
      result: {
        patientIntake: results,
        timestamp: new Date().toISOString()
      }
    });
  };

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

Form with Conditional Logic

import { Form } from "@samplehc/ui/components";
import { useState } from "react";

function ConditionalForm() {
  const [hasInsurance, setHasInsurance] = useState(false);

  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">
      <label className="flex items-center space-x-2">
        <input 
          type="checkbox"
          checked={hasInsurance}
          onChange={(e) => setHasInsurance(e.target.checked)}
        />
        <span>Patient has insurance</span>
      </label>
      
      <Form 
        elements={[...baseElements, ...insuranceElements]}
        onSubmit={(results) => console.log(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.

Network Issues: Temporary network issues are automatically retried. Persistent failures will show user-friendly error messages.

File Size Limits: Large files are automatically handled, but consider breaking very large ZIP files into smaller chunks for better user experience.

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
  • Task State: Use with useTaskState to persist form data across workflow steps
  • Progress Tracking: Built-in loading states and progress indicators
  • Error Recovery: Robust error handling with retry mechanisms
// Form data automatically persists across workflow steps
const [patientData, setPatientData] = useTaskState("patient", {});

<Form 
  onSubmit={(results) => {
    setPatientData(results);  // Persists automatically
    handleComplete({ result: results });  // Advances workflow
  }}
/>