import React from 'react';
import { ExtendedForm } from '../src/ExtendedForm';
import { RJSFSchema, UiSchema } from '@rjsf/utils';
import { 
  createDynamicArrayItemsUiSchema, 
  arrayItemPatterns 
} from '../src/conditionals/v2/utils/dynamicArrayItems';

const schema: RJSFSchema = {
  type: 'object',
  properties: {
    directors: {
      type: 'array',
      title: 'Company Directors',
      items: {
        type: 'object',
        required: ['name', 'directorType'],
        properties: {
          name: { type: 'string', title: 'Name' },
          directorType: {
            type: 'string',
            title: 'Director Type',
            enum: ['executive', 'non-executive'],
            enumNames: ['Executive', 'Non-Executive']
          },
          executiveRole: {
            type: 'string',
            title: 'Executive Role',
            enum: ['CEO', 'CFO', 'CTO', 'COO', 'Other'],
            enumNames: ['CEO', 'CFO', 'CTO', 'COO', 'Other']
          },
          otherRoleDetails: {
            type: 'string',
            title: 'Other Role Details'
          },
          hasShareholding: { type: 'boolean', title: 'Has Shareholding?' },
          shareholdingPercentage: { 
            type: 'number', 
            title: 'Shareholding %',
            minimum: 0,
            maximum: 100
          }
        }
      }
    }
  }
};

// Base UI schema for all array items
const baseItemUiSchema: UiSchema = {
  'ui:order': ['name', 'directorType', 'executiveRole', 'otherRoleDetails', 'hasShareholding', 'shareholdingPercentage'],
  name: {
    'ui:widget': 'text',
    'ui:placeholder': 'Enter director name'
  },
  directorType: {
    'ui:widget': 'select'
  },
  executiveRole: {
    'ui:widget': 'select'
  },
  otherRoleDetails: {
    'ui:widget': 'text',
    'ui:placeholder': 'Specify other role'
  },
  hasShareholding: {
    'ui:widget': 'checkbox'
  },
  shareholdingPercentage: {
    'ui:widget': 'updown'
  }
};

// Create dynamic UI schema using the utility
const uiSchema: UiSchema = {
  directors: {
    items: createDynamicArrayItemsUiSchema(
      baseItemUiSchema,
      (itemData, index) => {
        const conditionalUi: Partial<UiSchema> = {};
        
        // Three-level conditional dependency chain
        // Level 1: Director type determines if executive role is shown
        if (itemData?.directorType !== 'executive') {
          conditionalUi.executiveRole = { 'ui:widget': 'hidden' };
          // Also hide dependent field since parent is hidden
          conditionalUi.otherRoleDetails = { 'ui:widget': 'hidden' };
        } else {
          // Level 2: Executive role determines if other role details is shown
          if (itemData?.executiveRole !== 'Other') {
            conditionalUi.otherRoleDetails = { 'ui:widget': 'hidden' };
          }
        }
        
        // Hide shareholding percentage if not a shareholder
        if (!itemData?.hasShareholding) {
          conditionalUi.shareholdingPercentage = { 'ui:widget': 'hidden' };
        }
        
        // Add special styling for first director
        if (index === 0) {
          conditionalUi['ui:classNames'] = 'primary-director';
          conditionalUi['ui:title'] = 'Primary Director';
        }
        
        return conditionalUi;
      }
    )
  }
};

export function DynamicArrayItemsExample() {
  const [formData, setFormData] = React.useState({
    directors: [
      { 
        name: 'John Doe', 
        directorType: 'executive', 
        executiveRole: 'CEO', 
        hasShareholding: true, 
        shareholdingPercentage: 51 
      },
      { 
        name: 'Jane Smith', 
        directorType: 'executive', 
        executiveRole: 'Other', 
        otherRoleDetails: 'Head of Innovation',
        hasShareholding: true,
        shareholdingPercentage: 30
      },
      { 
        name: 'Bob Johnson', 
        directorType: 'non-executive',
        hasShareholding: false
      }
    ]
  });

  return (
    <div>
      <h1>Dynamic Array Items Example</h1>
      <p>
        This example demonstrates O(n) performance for array conditionals using 
        the RJSF fork's dynamic uiSchema.items capability. It showcases:
      </p>
      <ul>
        <li>Three-level conditional dependencies (Director Type → Executive Role → Other Role Details)</li>
        <li>Enum-based conditions for more realistic form patterns</li>
        <li>The common "Other" option pattern with additional text field</li>
        <li>Multiple independent conditionals within each array item</li>
      </ul>
      
      <ExtendedForm
        schema={schema}
        uiSchema={uiSchema}
        formData={formData}
        onChange={({ formData }) => setFormData(formData)}
      />
      
      <div style={{ marginTop: '20px' }}>
        <h3>Performance Benefits:</h3>
        <ul>
          <li>Each array item's UI is calculated independently</li>
          <li>No wildcard pattern expansion needed</li>
          <li>O(n) complexity instead of O(n²)</li>
          <li>Scales efficiently with large arrays</li>
        </ul>
      </div>
    </div>
  );
}

// Alternative example using helper patterns
export function DynamicArrayPatternsExample() {
  const uiSchemaWithPatterns: UiSchema = {
    directors: {
      items: createDynamicArrayItemsUiSchema(
        baseItemUiSchema,
        (itemData, index) => {
          // Combine multiple pattern helpers for cleaner code
          const hideShareholding = arrayItemPatterns.hideField(
            'shareholdingPercentage',
            (data) => !data?.hasShareholding
          )(itemData, index);
          
          const hideExecutiveRole = arrayItemPatterns.hideField(
            'executiveRole',
            (data) => data?.directorType !== 'executive'
          )(itemData, index);
          
          const hideOtherRoleDetails = arrayItemPatterns.hideField(
            'otherRoleDetails',
            (data) => data?.directorType !== 'executive' || data?.executiveRole !== 'Other'
          )(itemData, index);
          
          return {
            ...hideShareholding,
            ...hideExecutiveRole,
            ...hideOtherRoleDetails
          };
        }
      )
    }
  };
  
  return (
    <ExtendedForm
      schema={schema}
      uiSchema={uiSchemaWithPatterns}
    />
  );
}