import type { EmailTemplateDefinition, VariableField } from '../email/types'

function FieldInput({
  field,
  value,
  onChange,
}: {
  field: VariableField
  value: string
  onChange: (v: string) => void
}) {
  const type = field.inputType ?? 'text'

  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontSize: 12, opacity: 0.8 }}>{field.label}</span>
      <input
        type={type === 'number' ? 'number' : type === 'date' ? 'date' : 'text'}
        value={value}
        placeholder={field.placeholder || ''}
        onChange={(e) => onChange(e.target.value)}
        style={{ padding: '8px 10px', border: '1px solid #e5e7eb', borderRadius: 8 }}
      />
    </label>
  )
}

export function VariablesForm({
  template,
  data,
  onChange,
}: {
  template: EmailTemplateDefinition
  data: Record<string, string>
  onChange: (next: Record<string, string>) => void
}) {
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <h2 style={{ margin: 0, fontSize: 14 }}>Template variables</h2>
        <div style={{ fontSize: 12, opacity: 0.7 }}>{template.variables.length} fields</div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: 12 }}>
        {template.variables.map((f) => (
          <FieldInput
            key={f.key}
            field={f}
            value={data[f.key] ?? ''}
            onChange={(v) => onChange({ ...data, [f.key]: v })}
          />
        ))}
      </div>
    </div>
  )
}
