import { useEffect, useState } from 'react'
import { MAX_TOP_PATROL_TAGS, sanitizePatrolKeyword } from '../lib/knowledgeGraph'
import { Button, Input } from './ui'

type PatrolKeywordsEditorProps = {
  keywords: string[]
  onSave: (keywords: string[]) => Promise<void>
  hint?: string
}

export function PatrolKeywordsEditor({ keywords, onSave, hint }: PatrolKeywordsEditorProps) {
  const [draft, setDraft] = useState<string[]>(keywords)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    setDraft(keywords)
  }, [keywords])

  const dirty = JSON.stringify(draft) !== JSON.stringify(keywords)

  const updateItem = (index: number, value: string) => {
    setDraft((prev) => prev.map((item, i) => (i === index ? value : item)))
  }

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

  const addItem = () => {
    if (draft.length >= MAX_TOP_PATROL_TAGS) return
    setDraft((prev) => [...prev, ''])
  }

  const save = async () => {
    setSaving(true)
    setError('')
    try {
      const cleaned = draft
        .map((item) => sanitizePatrolKeyword(item))
        .filter((item) => item.length > 0)
      const unique = [...new Set(cleaned)].slice(0, MAX_TOP_PATROL_TAGS)
      await onSave(unique)
      setDraft(unique)
    } catch (e) {
      setError(e instanceof Error ? e.message : '儲存失敗')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="space-y-3">
      {hint ? <p className="text-sm text-ink-secondary">{hint}</p> : null}
      <ol className="hx-patrol-editor">
        {draft.map((item, index) => (
          <li key={`patrol-${index}`} className="hx-patrol-editor__row">
            <span className="hx-patrol-picks__rank">{index + 1}</span>
            <Input
              value={item}
              onChange={(e) => updateItem(index, e.target.value)}
              placeholder="例：化療 沐浴乳（6～14 字短句）"
              className="flex-1 text-[15px]"
            />
            <Button variant="ghost" type="button" onClick={() => removeItem(index)}>
              移除
            </Button>
          </li>
        ))}
      </ol>
      <div className="hx-research-actions hx-research-actions--inline">
        <Button
          variant="ghost"
          type="button"
          onClick={addItem}
          disabled={draft.length >= MAX_TOP_PATROL_TAGS}
        >
          新增關鍵字
        </Button>
        <Button variant="soft" type="button" onClick={() => void save()} disabled={!dirty || saving}>
          {saving ? '儲存中…' : '儲存關鍵字'}
        </Button>
        <span className="text-sm text-muted">
          最多 {MAX_TOP_PATROL_TAGS} 組，像真人會在 Threads 搜尋的短句
        </span>
      </div>
      {error ? <p className="text-sm text-danger">{error}</p> : null}
    </div>
  )
}