import { CTA_TYPE_OPTIONS, parseProductContext, serializeProductContext, type ProductContextFields } from '../lib/productContext'
import { Field, Input, Select, Textarea } from './ui'

type ProductContextFormProps = {
  value: string
  onChange: (serialized: string) => void
  compact?: boolean
}

export function ProductContextForm({ value, onChange, compact = false }: ProductContextFormProps) {
  const fields = parseProductContext(value)

  const update = (patch: Partial<ProductContextFields>) => {
    onChange(serializeProductContext({ ...fields, ...patch }))
  }

  return (
    <div className={compact ? 'grid gap-3' : 'grid gap-4'}>
      <div className="grid gap-3 sm:grid-cols-2">
        <Field label="品牌名稱">
          <Input
            value={fields.brand}
            onChange={(e) => update({ brand: e.target.value })}
            placeholder="例：kahu"
            data-islander-label="置入品牌"
          />
        </Field>
        <Field label="產品名稱">
          <Input
            value={fields.product}
            onChange={(e) => update({ product: e.target.value })}
            placeholder="例：寵物洗毛精"
            data-islander-label="置入產品"
          />
        </Field>
      </div>
      <Field label="產品特色／能解決什麼">
        <Textarea
          rows={compact ? 2 : 3}
          value={fields.features}
          onChange={(e) => update({ features: e.target.value })}
          placeholder="例：溫和無香料、適合皮膚敏感的狗"
          data-islander-label="產品特色"
        />
      </Field>
      <Field label="置入語氣（選填）">
        <Textarea
          rows={2}
          value={fields.placementTone ?? ''}
          onChange={(e) => update({ placementTone: e.target.value })}
          placeholder="例：像朋友分享，先回應困擾再順帶提到"
        />
      </Field>
      <div className="grid gap-3 sm:grid-cols-2">
        <Field label="留言 CTA 類型（選填）">
          <Select
            value={fields.ctaType ?? 'none'}
            onChange={(e) => update({ ctaType: e.target.value as ProductContextFields['ctaType'] })}
          >
            {CTA_TYPE_OPTIONS.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </Select>
        </Field>
        {fields.ctaType === 'link' ? (
          <Field label="CTA 連結網址">
            <Input
              value={fields.ctaUrl ?? ''}
              onChange={(e) => update({ ctaUrl: e.target.value })}
              placeholder="https://"
              data-islander-label="CTA網址"
            />
          </Field>
        ) : null}
      </div>
    </div>
  )
}