/**
 * On/Off 토글 스위치 필드
 *
 * properties: { onLabel, offLabel, onValue, offValue }
 * 저장값: onValue/offValue (기본: "true"/"false")
 */

'use client';

import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import type { DynamicFieldRendererProps, ToggleConfig } from '../types';

export function ToggleField({
  field,
  value,
  onChange,
  error,
  disabled,
}: DynamicFieldRendererProps) {
  const fieldKey = field.field_key || `field_${field.id}`;
  const config = (field.properties || {}) as ToggleConfig;
  const onLabel = config.onLabel || 'ON';
  const offLabel = config.offLabel || 'OFF';
  const onValue = config.onValue || 'true';
  const offValue = config.offValue || 'false';

  const isChecked = value === onValue || value === true || value === 'true';

  const handleChange = (checked: boolean) => {
    onChange(checked ? onValue : offValue);
  };

  return (
    <div>
      <Label htmlFor={fieldKey}>
        {field.field_name}
        {field.is_required && <span className="text-red-500"> *</span>}
      </Label>
      <div className="flex items-center gap-3 mt-2">
        <Switch
          id={fieldKey}
          checked={isChecked}
          onCheckedChange={handleChange}
          disabled={disabled}
        />
        <span className="text-sm text-muted-foreground">
          {isChecked ? onLabel : offLabel}
        </span>
      </div>
      {error && (
        <p className="text-xs text-red-500 mt-1">{error}</p>
      )}
      {!error && field.description && (
        <p className="text-xs text-muted-foreground mt-1">
          * {field.description}
        </p>
      )}
    </div>
  );
}
