# Questionnaire Form Component

A component for rendering FHIR-based questionnaires with multi-page navigation and various input types.

## Features

- Renders FHIR-compatible questionnaires
- Supports multiple page navigation
- Handles various question types:
  - Text/string input
  - Boolean (checkbox)
  - Choice (radio buttons)
  - Date
  - Number
- Provides form validation
- Supports conditional questions with default values
- Returns FHIR-compatible QuestionnaireResponse

## Usage

```tsx
import { QuestionnaireForm, QuestionnaireResponse } from "@ovok/native";

const MyComponent = () => {
  const questionnaire = {
    resourceType: "Questionnaire",
    id: "example-questionnaire",
    title: "My Questionnaire",
    status: "active",
    item: [
      {
        linkId: "page-1",
        text: "First Page",
        type: "group",
        item: [
          {
            linkId: "question-1",
            text: "What is your name?",
            type: "string",
            required: true,
            helperText: "Please enter your full name",
            placeholder: "John Doe",
          },
        ],
      },
    ],
  };

  const handleSubmit = (response: QuestionnaireResponse) => {
    console.log("Form submitted:", response);
  };

  return (
    <QuestionnaireForm questionnaire={questionnaire} onSubmit={handleSubmit} />
  );
};
```

## Props

| Prop          | Type                                                                                                       | Description                                           |
| ------------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| questionnaire | Questionnaire                                                                                              | The FHIR Questionnaire resource to render             |
| onSubmit      | (values: QuestionnaireFormValues, formikHelpers?: FormikHelpers<QuestionnaireFormValues>) => Promise<void> | Optional callback for form submission                 |
| onSuccess     | (response: QuestionnaireResponse) => void                                                                  | Optional callback when form is submitted successfully |
| onError       | (error: Error) => void                                                                                     | Optional callback when form submission fails          |
| initialValues | Partial<QuestionnaireFormValues>                                                                           | Optional initial values for the form                  |
| children      | ReactNode                                                                                                  | Child components for custom layout                    |
| style         | ViewStyle                                                                                                  | Optional styles for the container                     |
| testID        | string                                                                                                     | Test ID for testing                                   |

Note: You must provide either `onSubmit` OR both `onSuccess` and `onError` callbacks, but not both.

## Extended Properties

In addition to standard FHIR QuestionnaireItem properties, the component supports these additional UI properties:

| Property        | Type    | Description                                   |
| --------------- | ------- | --------------------------------------------- |
| helperText      | string  | Help text displayed below the input           |
| placeholder     | string  | Placeholder text for text inputs              |
| initialSelected | boolean | For choice items, sets default selected state |

## Conditional Questions

The component supports conditional questions using FHIR's `enableWhen` property. When conditional questions become visible, any choice options with `initialSelected` set to true will be automatically selected:

```tsx
const questionnaire = {
  // ...
  item: [
    {
      linkId: "has-pets",
      text: "Do you have any pets?",
      type: "boolean",
      required: true,
    },
    {
      linkId: "pet-type",
      text: "What kind of pet do you have?",
      type: "choice",
      enableWhen: [
        {
          question: "has-pets",
          operator: "=",
          answerBoolean: true,
        },
      ],
      answerOption: [
        {
          valueCoding: {
            code: "dog",
            display: "Dog",
          },
        },
        {
          valueCoding: {
            code: "cat",
            display: "Cat",
          },
          initialSelected: true, // This option will be selected by default
        },
        {
          valueCoding: {
            code: "other",
            display: "Other",
          },
        },
      ],
    },
  ],
};
```

## Structure

The QuestionnaireForm uses a compound component pattern with the following structure:

- **QuestionnaireForm**: Main container component
  - **QuestionnaireForm.Header**: Form header section
    - **QuestionnaireForm.Header.Title**: Form title
    - **QuestionnaireForm.Header.Subtitle**: Form subtitle/progress
  - **QuestionnaireForm.Content**: Form content section
    - **QuestionnaireForm.Content.Item**: Question item renderer
    - **QuestionnaireForm.Content.Error**: Error message display
  - **QuestionnaireForm.Navigation**: Navigation controls
    - **QuestionnaireForm.Navigation.PreviousButton**: Previous page button
    - **QuestionnaireForm.Navigation.NextButton**: Next page button
    - **QuestionnaireForm.Navigation.SubmitButton**: Form submission button

## Field Types

The form supports various field types through specialized components:

- **QuestionnaireTextField**: Text input with keyboard type support
- **QuestionnaireChoiceField**: Radio button selection
- **QuestionnaireBooleanField**: Yes/No checkbox
- **QuestionnaireDateField**: Date picker
- **QuestionnaireItemRenderer**: Dynamic field type renderer

## Context and Hooks

The form provides a context and hooks for advanced customization:

- **useQuestionnaireForm**: Hook to access form context and state
- **QuestionnaireFormContext**: Context provider for form state
- **QuestionnaireFormProvider**: Provider component managing form logic

## Utilities

The form includes utility classes for various operations:

- **FormUtils**: Form initialization and data transformation
- **ConditionUtils**: Conditional question handling
- **FormValidation**: Form validation logic
- **QuestionnaireSubmitUtils**: Response creation and submission

## Upgraded QuestionnaireForm API

The QuestionnaireForm component has been refactored to use a compound component pattern, making it more customizable and flexible.

### Basic Usage

```tsx
import { QuestionnaireForm } from "@ovok/native";

const MyComponent = () => {
  const handleSubmit = (response) => {
    // Handle the questionnaire response
  };

  return (
    <QuestionnaireForm questionnaire={questionnaire} onSubmit={handleSubmit}>
      <QuestionnaireForm.Header />
      <QuestionnaireForm.Content />
      <QuestionnaireForm.Navigation />
    </QuestionnaireForm>
  );
};
```

### Advanced Customization

```tsx
import { QuestionnaireForm } from "@ovok/native";
import { View } from "react-native";

const MyComponent = () => {
  return (
    <QuestionnaireForm questionnaire={questionnaire} onSubmit={handleSubmit}>
      <QuestionnaireForm.Header style={{ marginBottom: 24 }}>
        <QuestionnaireForm.Header.Title style={{ fontSize: 24 }} />
        <QuestionnaireForm.Header.Subtitle
          prefix="Step"
          style={{ color: "gray" }}
        />
      </QuestionnaireForm.Header>

      <View style={{ padding: 16 }}>
        <QuestionnaireForm.Content style={{ paddingHorizontal: 20 }}>
          <QuestionnaireForm.Content.Item />
          <QuestionnaireForm.Content.Error style={{ color: "darkred" }} />
        </QuestionnaireForm.Content>
      </View>

      <QuestionnaireForm.Navigation style={{ padding: 16 }}>
        <QuestionnaireForm.Navigation.PreviousButton children="Go Back" />
        <QuestionnaireForm.Navigation.NextButton
          mode="contained"
          children="Continue"
        />
        <QuestionnaireForm.Navigation.SubmitButton
          mode="contained"
          children="Complete Survey"
        />
      </QuestionnaireForm.Navigation>
    </QuestionnaireForm>
  );
};
```

### API Reference

#### QuestionnaireForm Props

| Prop          | Type                                      | Description                         |
| ------------- | ----------------------------------------- | ----------------------------------- |
| questionnaire | Questionnaire                             | The questionnaire object to render  |
| onSubmit      | (response: QuestionnaireResponse) => void | Callback when the form is submitted |
| initialValues | QuestionnaireFormValues                   | Initial values for the form         |
| style         | StyleProp<ViewStyle>                      | Style for the container             |
| testID        | string                                    | Test ID for the component           |

#### QuestionnaireForm.Header Props

| Prop     | Type                 | Description                        |
| -------- | -------------------- | ---------------------------------- |
| style    | StyleProp<ViewStyle> | Style for the header container     |
| children | ReactNode            | Header children components         |
| ...rest  | ViewProps            | All other View props are supported |

#### QuestionnaireForm.Header.Title Props

| Prop     | Type                 | Description                        |
| -------- | -------------------- | ---------------------------------- |
| style    | StyleProp<TextStyle> | Style for the title text           |
| children | ReactNode            | Custom title content               |
| ...rest  | TextProps            | All other Text props are supported |

#### QuestionnaireForm.Header.Subtitle Props

| Prop     | Type                 | Description                        |
| -------- | -------------------- | ---------------------------------- |
| style    | StyleProp<TextStyle> | Style for the subtitle text        |
| prefix   | string               | Prefix for subtitle (Question)     |
| children | ReactNode            | Custom subtitle content            |
| ...rest  | TextProps            | All other Text props are supported |

#### QuestionnaireForm.Content Props

| Prop     | Type                 | Description                        |
| -------- | -------------------- | ---------------------------------- |
| style    | StyleProp<ViewStyle> | Style for the content container    |
| children | ReactNode            | Content children components        |
| ...rest  | ViewProps            | All other View props are supported |

#### QuestionnaireForm.Content.Item Props

| Prop    | Type                 | Description                        |
| ------- | -------------------- | ---------------------------------- |
| style   | StyleProp<ViewStyle> | Style for the item                 |
| testID  | string               | Test ID for the item               |
| ...rest | ViewProps            | All other View props are supported |

#### QuestionnaireForm.Content.Error Props

| Prop     | Type                 | Description                        |
| -------- | -------------------- | ---------------------------------- |
| style    | StyleProp<TextStyle> | Style for the error message        |
| children | ReactNode            | Custom error content               |
| ...rest  | TextProps            | All other Text props are supported |

#### QuestionnaireForm.Navigation Props

| Prop                | Type                 | Description                         |
| ------------------- | -------------------- | ----------------------------------- |
| style               | StyleProp<ViewStyle> | Style for the navigation container  |
| children            | ReactNode            | Navigation children components      |
| previousButtonProps | Partial<ButtonProps> | Props passed to the Previous button |
| nextButtonProps     | Partial<ButtonProps> | Props passed to the Next button     |
| submitButtonProps   | Partial<ButtonProps> | Props passed to the Submit button   |
| ...rest             | ViewProps            | All other View props are supported  |

#### QuestionnaireForm.Navigation.PreviousButton Props

| Prop     | Type        | Description                          |
| -------- | ----------- | ------------------------------------ |
| children | ReactNode   | Custom button text                   |
| ...rest  | ButtonProps | All other Button props are supported |

#### QuestionnaireForm.Navigation.NextButton Props

| Prop     | Type        | Description                          |
| -------- | ----------- | ------------------------------------ |
| children | ReactNode   | Custom button text                   |
| ...rest  | ButtonProps | All other Button props are supported |

#### QuestionnaireForm.Navigation.SubmitButton Props

| Prop     | Type        | Description                          |
| -------- | ----------- | ------------------------------------ |
| children | ReactNode   | Custom button text                   |
| ...rest  | ButtonProps | All other Button props are supported |

## Architecture Improvements

The QuestionnaireForm has been optimized for performance and maintainability:

1. **Type Safety**: Stronger typing with custom types like `ResponseValues` and `QuestionnaireFormValues`
2. **Component Separation**: Logic separated into focused utility functions and hooks
3. **Performance**: Efficient re-rendering with proper React dependency management
4. **Conditional Logic**: Improved handling of conditional questions with automatic initialization

## New Features and Improvements

### 1. Enhanced Form Submission

- Added support for both callback and promise-based submission handling
- New `onSuccess` and `onError` callbacks for better error handling
- Improved type safety with `QuestionnaireResponse` type

### 2. Navigation Improvements

- Added navigation state management with `useQuestionnaireNavigationState` hook
- Improved handling of conditional questions during navigation
- Better error handling and validation during navigation
- Added support for tracking total items and current item number

### 3. Field Improvements

- Enhanced keyboard type support for text fields
- Improved field wrapper component with better styling options
- Better handling of boolean fields with empty string values

### 4. Type Safety Enhancements

- Added `ExtendedQuestionnaireItem` type for better type safety
- Improved `QuestionnaireFormValues` type with better null handling
- Added proper typing for navigation context and handlers

### 5. Performance Optimizations

- Memoized navigation state calculations
- Optimized re-renders with React.memo
- Improved form validation performance
