import { Button, Input } from './ui'

type StringListEditorProps = {
  items: string[]
  onChange: (items: string[]) => void
  placeholder?: string
  addLabel?: string
  maxItems?: number
}

export function StringListEditor({
  items,
  onChange,
  placeholder = '輸入一項',
  addLabel = '新增一項',
  maxItems,
}: StringListEditorProps) {
  const updateItem = (index: number, value: string) => {
    onChange(items.map((item, i) => (i === index ? value : item)))
  }

  const removeItem = (index: number) => {
    onChange(items.filter((_, i) => i !== index))
  }

  const addItem = () => {
    if (maxItems !== undefined && items.length >= maxItems) return
    onChange([...items, ''])
  }

  return (
    <div className="space-y-3">
      {items.length > 0 ? (
        <ol className="hx-string-list-editor">
          {items.map((item, index) => (
            <li key={`item-${index}`} className="hx-string-list-editor__row">
              <span className="hx-research-reader__list-index">{index + 1}</span>
              <Input
                value={item}
                onChange={(e) => updateItem(index, e.target.value)}
                placeholder={placeholder}
                className="flex-1 text-[15px]"
              />
              <Button variant="ghost" type="button" onClick={() => removeItem(index)}>
                移除
              </Button>
            </li>
          ))}
        </ol>
      ) : (
        <p className="text-sm text-ink-secondary">尚無項目，可按下方新增。</p>
      )}
      <div className="hx-research-actions hx-research-actions--inline">
        <Button
          variant="ghost"
          type="button"
          onClick={addItem}
          disabled={maxItems !== undefined && items.length >= maxItems}
        >
          {addLabel}
        </Button>
      </div>
    </div>
  )
}