# Toggle

A toggle switch component that allows users to switch between two states (on/off, enabled/disabled). It provides a visual alternative to checkboxes for boolean inputs and includes flexible label positioning options. The component integrates seamlessly with forms and supports both controlled and uncontrolled usage patterns.

## Aliases

- Toggle
- Switch
- ToggleSwitch

## Props Breakdown

**Extends:** `InputHTMLAttributes<HTMLInputElement>` (excluding `type`, `value`, `checked`) + `ControlledFormComponentProps<boolean>`

| Prop | Type | Default | Required | Description |
|------|------|---------|----------|-------------|
| `children` | `ReactNode` | `undefined` | No | The label of the toggle |
| `labelAlignment` | `'Left' \| 'Right'` | `'Left'` | No | Alignment of the label |
| `initialValue` | `boolean` | `undefined` | No | The initial value for the field |
| `checked` | `boolean` | `undefined` | No | The initial value for the field |
| `value` | `boolean` | `undefined` | No | The current value of the form field |
| `onValueChange` | `(value: boolean) => void` | `undefined` | No | Callback function that is called when the field value changes |
| `disabled` | `boolean` | `false` | No | Whether the form field is disabled and cannot be interacted with |
| `required` | `boolean` | `false` | No | Whether the form field must have a value |
| `invalid` | `boolean` | `false` | No | Whether the form field's current value is invalid |
| `id` | `string` | `undefined` | No | Id for the form field |
| `name` | `string` | `undefined` | No | Name attribute for the toggle |

Plus all standard HTML input attributes (onChange, onFocus, onBlur, aria-*, data-*, etc.).

## Examples

### Basic Toggle

```tsx
import { Toggle } from '@delightui/components';

function BasicToggleExample() {
  const [isEnabled, setIsEnabled] = useState(false);

  return (
    <div>
      <p>Status: {isEnabled ? 'Enabled' : 'Disabled'}</p>
      <Toggle
        value={isEnabled}
        onValueChange={setIsEnabled}
      >
        Enable notifications
      </Toggle>
    </div>
  );
}
```

### Label Alignment

```tsx
import { Toggle } from '@delightui/components';

function LabelAlignmentExample() {
  const [leftToggle, setLeftToggle] = useState(false);
  const [rightToggle, setRightToggle] = useState(true);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
      <Toggle
        value={leftToggle}
        onValueChange={setLeftToggle}
        labelAlignment="Left"
      >
        Label on the left
      </Toggle>
      
      <Toggle
        value={rightToggle}
        onValueChange={setRightToggle}
        labelAlignment="Right"
      >
        Label on the right
      </Toggle>
    </div>
  );
}
```

### Form Integration

```tsx
import { Form, FormField, Toggle, Button } from '@delightui/components';

function ToggleFormExample() {
  const handleSubmit = (data: any) => {
    console.log('Form submitted:', data);
  };

  return (
    <Form onSubmit={handleSubmit}>
      <FormField
        name="emailNotifications"
        label="Email Notifications"
      >
        <Toggle initialValue={true}>
          Receive email notifications
        </Toggle>
      </FormField>

      <FormField
        name="smsNotifications"
        label="SMS Notifications"
      >
        <Toggle initialValue={false}>
          Receive SMS notifications
        </Toggle>
      </FormField>

      <FormField
        name="marketing"
        label="Marketing Communications"
      >
        <Toggle initialValue={false}>
          Receive marketing emails
        </Toggle>
      </FormField>

      <FormField
        name="twoFactor"
        label="Security"
        required
      >
        <Toggle initialValue={true}>
          Enable two-factor authentication
        </Toggle>
      </FormField>

      <Button type="submit">
        Save Preferences
      </Button>
    </Form>
  );
}
```

### Settings Panel

```tsx
import { Toggle, Text } from '@delightui/components';

function SettingsPanelExample() {
  const [settings, setSettings] = useState({
    darkMode: false,
    notifications: true,
    autoSave: true,
    soundEffects: false,
    analytics: false
  });

  const updateSetting = (key: string, value: boolean) => {
    setSettings(prev => ({ ...prev, [key]: value }));
  };

  return (
    <div style={{ 
      border: '1px solid #ccc', 
      borderRadius: '8px', 
      padding: '20px',
      maxWidth: '400px'
    }}>
      <Text weight="bold" size="large" style={{ marginBottom: '20px' }}>
        Application Settings
      </Text>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
        <div>
          <Toggle
            value={settings.darkMode}
            onValueChange={(value) => updateSetting('darkMode', value)}
          >
            Dark Mode
          </Toggle>
          <Text size="small" color="secondary" style={{ marginTop: '4px', marginLeft: '28px' }}>
            Switch to dark theme for better viewing in low light
          </Text>
        </div>

        <div>
          <Toggle
            value={settings.notifications}
            onValueChange={(value) => updateSetting('notifications', value)}
          >
            Push Notifications
          </Toggle>
          <Text size="small" color="secondary" style={{ marginTop: '4px', marginLeft: '28px' }}>
            Receive notifications about important updates
          </Text>
        </div>

        <div>
          <Toggle
            value={settings.autoSave}
            onValueChange={(value) => updateSetting('autoSave', value)}
          >
            Auto-save
          </Toggle>
          <Text size="small" color="secondary" style={{ marginTop: '4px', marginLeft: '28px' }}>
            Automatically save your work every 5 minutes
          </Text>
        </div>

        <div>
          <Toggle
            value={settings.soundEffects}
            onValueChange={(value) => updateSetting('soundEffects', value)}
          >
            Sound Effects
          </Toggle>
          <Text size="small" color="secondary" style={{ marginTop: '4px', marginLeft: '28px' }}>
            Play sounds for notifications and interactions
          </Text>
        </div>

        <div>
          <Toggle
            value={settings.analytics}
            onValueChange={(value) => updateSetting('analytics', value)}
          >
            Analytics
          </Toggle>
          <Text size="small" color="secondary" style={{ marginTop: '4px', marginLeft: '28px' }}>
            Help improve our service by sharing usage data
          </Text>
        </div>
      </div>
    </div>
  );
}
```

### Feature Toggles

```tsx
import { Toggle, Text, Button } from '@delightui/components';

function FeatureTogglesExample() {
  const [features, setFeatures] = useState({
    betaFeatures: false,
    experimentalUI: false,
    advancedMode: false,
    debugMode: false
  });

  const [showWarning, setShowWarning] = useState(false);

  const updateFeature = (key: string, value: boolean) => {
    if (key === 'debugMode' && value) {
      setShowWarning(true);
    } else {
      setShowWarning(false);
    }
    setFeatures(prev => ({ ...prev, [key]: value }));
  };

  return (
    <div style={{ maxWidth: '500px' }}>
      <Text weight="bold" size="large" style={{ marginBottom: '16px' }}>
        Feature Toggles
      </Text>
      
      <Text size="small" color="secondary" style={{ marginBottom: '20px' }}>
        Enable or disable experimental features. Some features may be unstable.
      </Text>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
        <div style={{ 
          padding: '16px', 
          border: '1px solid #e0e0e0', 
          borderRadius: '8px',
          backgroundColor: features.betaFeatures ? '#f0f8ff' : '#f9f9f9'
        }}>
          <Toggle
            value={features.betaFeatures}
            onValueChange={(value) => updateFeature('betaFeatures', value)}
          >
            <Text weight="medium">Beta Features</Text>
          </Toggle>
          <Text size="small" color="secondary" style={{ marginTop: '8px', marginLeft: '28px' }}>
            Access to features currently in beta testing
          </Text>
        </div>

        <div style={{ 
          padding: '16px', 
          border: '1px solid #e0e0e0', 
          borderRadius: '8px',
          backgroundColor: features.experimentalUI ? '#fff8e1' : '#f9f9f9'
        }}>
          <Toggle
            value={features.experimentalUI}
            onValueChange={(value) => updateFeature('experimentalUI', value)}
          >
            <Text weight="medium">Experimental UI</Text>
          </Toggle>
          <Text size="small" color="secondary" style={{ marginTop: '8px', marginLeft: '28px' }}>
            Try out new user interface designs and layouts
          </Text>
        </div>

        <div style={{ 
          padding: '16px', 
          border: '1px solid #e0e0e0', 
          borderRadius: '8px',
          backgroundColor: features.advancedMode ? '#e8f5e8' : '#f9f9f9'
        }}>
          <Toggle
            value={features.advancedMode}
            onValueChange={(value) => updateFeature('advancedMode', value)}
          >
            <Text weight="medium">Advanced Mode</Text>
          </Toggle>
          <Text size="small" color="secondary" style={{ marginTop: '8px', marginLeft: '28px' }}>
            Show advanced options and configuration settings
          </Text>
        </div>

        <div style={{ 
          padding: '16px', 
          border: '1px solid #ffcdd2', 
          borderRadius: '8px',
          backgroundColor: features.debugMode ? '#ffebee' : '#f9f9f9'
        }}>
          <Toggle
            value={features.debugMode}
            onValueChange={(value) => updateFeature('debugMode', value)}
          >
            <Text weight="medium" color={features.debugMode ? 'error' : 'default'}>
              Debug Mode
            </Text>
          </Toggle>
          <Text size="small" color="secondary" style={{ marginTop: '8px', marginLeft: '28px' }}>
            Enable debugging tools and verbose logging
          </Text>
          
          {showWarning && (
            <div style={{ 
              marginTop: '12px', 
              padding: '8px 12px', 
              backgroundColor: '#fff3cd',
              border: '1px solid #ffeaa7',
              borderRadius: '4px'
            }}>
              <Text size="small" color="warning" weight="medium">
                Warning: Debug mode may impact performance and expose sensitive information.
              </Text>
            </div>
          )}
        </div>
      </div>

      <div style={{ marginTop: '24px', textAlign: 'center' }}>
        <Button onClick={() => console.log('Settings saved:', features)}>
          Save Settings
        </Button>
      </div>
    </div>
  );
}
```

### Disabled Toggles

```tsx
import { Toggle, Text } from '@delightui/components';

function DisabledTogglesExample() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
      <Text weight="bold" style={{ marginBottom: '8px' }}>
        Toggle States
      </Text>

      <Toggle value={false}>
        Normal toggle (off)
      </Toggle>

      <Toggle value={true}>
        Normal toggle (on)
      </Toggle>

      <Toggle value={false} disabled>
        Disabled toggle (off)
      </Toggle>

      <Toggle value={true} disabled>
        Disabled toggle (on)
      </Toggle>
    </div>
  );
}
```

### Privacy Settings

```tsx
import { Toggle, Text, Button } from '@delightui/components';

function PrivacySettingsExample() {
  const [privacy, setPrivacy] = useState({
    profileVisibility: true,
    showEmail: false,
    showPhone: false,
    allowMessages: true,
    shareData: false,
    trackingCookies: false
  });

  const updatePrivacy = (key: string, value: boolean) => {
    setPrivacy(prev => ({ ...prev, [key]: value }));
  };

  const getPrivacyScore = () => {
    const enabledCount = Object.values(privacy).filter(Boolean).length;
    const totalCount = Object.keys(privacy).length;
    return Math.round(((totalCount - enabledCount) / totalCount) * 100);
  };

  const privacyScore = getPrivacyScore();

  return (
    <div style={{ maxWidth: '600px' }}>
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        marginBottom: '20px'
      }}>
        <Text weight="bold" size="large">
          Privacy Settings
        </Text>
        <div style={{ 
          padding: '8px 16px', 
          borderRadius: '20px',
          backgroundColor: privacyScore > 60 ? '#d4edda' : privacyScore > 30 ? '#fff3cd' : '#f8d7da'
        }}>
          <Text size="small" weight="bold">
            Privacy Score: {privacyScore}%
          </Text>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
        <div>
          <Toggle
            value={privacy.profileVisibility}
            onValueChange={(value) => updatePrivacy('profileVisibility', value)}
            labelAlignment="Right"
          >
            <div>
              <Text weight="medium">Public Profile</Text>
              <Text size="small" color="secondary" style={{ display: 'block', marginTop: '2px' }}>
                Make your profile visible to other users
              </Text>
            </div>
          </Toggle>
        </div>

        <div>
          <Toggle
            value={privacy.showEmail}
            onValueChange={(value) => updatePrivacy('showEmail', value)}
            labelAlignment="Right"
          >
            <div>
              <Text weight="medium">Show Email Address</Text>
              <Text size="small" color="secondary" style={{ display: 'block', marginTop: '2px' }}>
                Display your email on your public profile
              </Text>
            </div>
          </Toggle>
        </div>

        <div>
          <Toggle
            value={privacy.showPhone}
            onValueChange={(value) => updatePrivacy('showPhone', value)}
            labelAlignment="Right"
          >
            <div>
              <Text weight="medium">Show Phone Number</Text>
              <Text size="small" color="secondary" style={{ display: 'block', marginTop: '2px' }}>
                Display your phone number on your public profile
              </Text>
            </div>
          </Toggle>
        </div>

        <div>
          <Toggle
            value={privacy.allowMessages}
            onValueChange={(value) => updatePrivacy('allowMessages', value)}
            labelAlignment="Right"
          >
            <div>
              <Text weight="medium">Allow Direct Messages</Text>
              <Text size="small" color="secondary" style={{ display: 'block', marginTop: '2px' }}>
                Let other users send you direct messages
              </Text>
            </div>
          </Toggle>
        </div>

        <div>
          <Toggle
            value={privacy.shareData}
            onValueChange={(value) => updatePrivacy('shareData', value)}
            labelAlignment="Right"
          >
            <div>
              <Text weight="medium">Data Sharing</Text>
              <Text size="small" color="secondary" style={{ display: 'block', marginTop: '2px' }}>
                Share anonymized usage data for product improvement
              </Text>
            </div>
          </Toggle>
        </div>

        <div>
          <Toggle
            value={privacy.trackingCookies}
            onValueChange={(value) => updatePrivacy('trackingCookies', value)}
            labelAlignment="Right"
          >
            <div>
              <Text weight="medium">Tracking Cookies</Text>
              <Text size="small" color="secondary" style={{ display: 'block', marginTop: '2px' }}>
                Allow tracking cookies for personalized advertising
              </Text>
            </div>
          </Toggle>
        </div>
      </div>

      <div style={{ 
        marginTop: '24px', 
        padding: '16px',
        backgroundColor: '#f8f9fa',
        borderRadius: '8px'
      }}>
        <Text size="small" color="secondary">
          Your privacy score reflects how much personal information you're sharing. 
          Higher scores indicate better privacy protection.
        </Text>
      </div>

      <div style={{ marginTop: '20px', textAlign: 'center' }}>
        <Button onClick={() => console.log('Privacy settings saved:', privacy)}>
          Save Privacy Settings
        </Button>
      </div>
    </div>
  );
}
```

### Permissions Toggle

```tsx
import { Toggle, Text, Icon } from '@delightui/components';

function PermissionsToggleExample() {
  const [permissions, setPermissions] = useState({
    camera: false,
    microphone: false,
    location: false,
    notifications: true,
    storage: true
  });

  const updatePermission = (key: string, value: boolean) => {
    setPermissions(prev => ({ ...prev, [key]: value }));
  };

  const permissionInfo = {
    camera: {
      icon: 'SearchFilled',
      title: 'Camera Access',
      description: 'Allow access to camera for photos and video calls'
    },
    microphone: {
      icon: 'SearchFilled',
      title: 'Microphone Access',
      description: 'Allow access to microphone for voice recording'
    },
    location: {
      icon: 'InfoFilled',
      title: 'Location Services',
      description: 'Allow access to your location for personalized content'
    },
    notifications: {
      icon: 'InfoFilled',
      title: 'Notifications',
      description: 'Show notifications for important updates'
    },
    storage: {
      icon: 'AddFilled',
      title: 'Storage Access',
      description: 'Allow access to device storage for file uploads'
    }
  };

  return (
    <div style={{ maxWidth: '500px' }}>
      <Text weight="bold" size="large" style={{ marginBottom: '16px' }}>
        App Permissions
      </Text>
      
      <Text size="small" color="secondary" style={{ marginBottom: '24px' }}>
        Control which features of your device this app can access.
      </Text>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
        {Object.entries(permissions).map(([key, value]) => {
          const info = permissionInfo[key as keyof typeof permissionInfo];
          
          return (
            <div 
              key={key}
              style={{ 
                display: 'flex', 
                alignItems: 'flex-start',
                gap: '12px',
                padding: '16px',
                border: '1px solid #e0e0e0',
                borderRadius: '8px',
                backgroundColor: value ? '#f0f8ff' : '#ffffff'
              }}
            >
              <Icon name={info.icon} style={{ marginTop: '4px', color: value ? '#007bff' : '#6c757d' }} />
              
              <div style={{ flex: 1 }}>
                <Text weight="medium" style={{ marginBottom: '4px' }}>
                  {info.title}
                </Text>
                <Text size="small" color="secondary" style={{ marginBottom: '8px' }}>
                  {info.description}
                </Text>
              </div>
              
              <Toggle
                value={value}
                onValueChange={(newValue) => updatePermission(key, newValue)}
              />
            </div>
          );
        })}
      </div>

      <div style={{ 
        marginTop: '20px',
        padding: '12px',
        backgroundColor: '#e9ecef',
        borderRadius: '8px'
      }}>
        <Text size="small" color="secondary">
          You can change these permissions at any time in your device settings.
        </Text>
      </div>
    </div>
  );
}
```

### Controlled vs Uncontrolled

```tsx
import { Toggle, Button, Text } from '@delightui/components';

function ControlledVsUncontrolledExample() {
  const [controlledValue, setControlledValue] = useState(false);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
      <div>
        <Text weight="bold" style={{ marginBottom: '12px' }}>
          Controlled Toggle
        </Text>
        <Text size="small" color="secondary" style={{ marginBottom: '12px' }}>
          Value is controlled by React state
        </Text>
        
        <Toggle
          value={controlledValue}
          onValueChange={setControlledValue}
        >
          Controlled toggle (value: {controlledValue.toString()})
        </Toggle>
        
        <Button 
          size="Small" 
          type="Outlined" 
          onClick={() => setControlledValue(!controlledValue)}
          style={{ marginTop: '8px' }}
        >
          Toggle Programmatically
        </Button>
      </div>

      <div>
        <Text weight="bold" style={{ marginBottom: '12px' }}>
          Uncontrolled Toggle
        </Text>
        <Text size="small" color="secondary" style={{ marginBottom: '12px' }}>
          Value is managed internally by the component
        </Text>
        
        <Toggle
          initialValue={true}
          onValueChange={(value) => console.log('Uncontrolled value changed:', value)}
        >
          Uncontrolled toggle with initial value
        </Toggle>
      </div>

      <div>
        <Text weight="bold" style={{ marginBottom: '12px' }}>
          Invalid State Example
        </Text>
        
        <Toggle
          value={true}
          invalid
        >
          Toggle with validation error
        </Toggle>
      </div>
    </div>
  );
}
```