import type { TemplateVariable } from '../types'

interface VariableFieldProps {
  variable: TemplateVariable
  value: unknown
  onChange: (value: unknown) => void
}

export default function VariableField({ variable, value, onChange }: VariableFieldProps) {
  const styleHint = variable.style_params
    ? [
        variable.style_params.font_name && `Font: ${variable.style_params.font_name}`,
        variable.style_params.font_size && `Size: ${variable.style_params.font_size}pt`,
        variable.style_params.bold && 'Bold',
        variable.style_params.alignment && `Align: ${variable.style_params.alignment}`,
      ]
        .filter(Boolean)
        .join(' · ')
    : null

  const renderInput = () => {
    switch (variable.field_type) {
      case 'textarea':
        return (
          <textarea
            value={(value as string) ?? ''}
            onChange={(e) => onChange(e.target.value)}
            required={variable.is_required}
          />
        )
      case 'number':
        return (
          <input
            type="number"
            value={(value as number) ?? ''}
            onChange={(e) => onChange(e.target.value ? Number(e.target.value) : '')}
            required={variable.is_required}
          />
        )
      case 'date':
        return (
          <input
            type="date"
            value={(value as string) ?? ''}
            onChange={(e) => onChange(e.target.value)}
            required={variable.is_required}
          />
        )
      default:
        return (
          <input
            type="text"
            value={(value as string) ?? ''}
            onChange={(e) => onChange(e.target.value)}
            required={variable.is_required}
          />
        )
    }
  }

  return (
    <div className="form-group">
      <label>
        {variable.label}
        {variable.is_required && ' *'}
      </label>
      {renderInput()}
      {styleHint && <div className="style-hint">Style: {styleHint}</div>}
    </div>
  )
}
