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

type PatrolNodeTagsEditorProps = {
  node: KnowledgeGraphNode
  onSave: (nodeId: string, relevance: string[], recency: string[]) => Promise<void>
}

export function PatrolNodeTagsEditor({ node, onSave }: PatrolNodeTagsEditorProps) {
  const [relevance, setRelevance] = useState(node.relevance_tags?.[0] ?? '')
  const [recency, setRecency] = useState(node.recency_tags?.[0] ?? '')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    setRelevance(node.relevance_tags?.[0] ?? '')
    setRecency(node.recency_tags?.[0] ?? '')
  }, [node.id, node.relevance_tags, node.recency_tags])

  const savedRelevance = node.relevance_tags?.[0] ?? ''
  const savedRecency = node.recency_tags?.[0] ?? ''
  const dirty = relevance.trim() !== savedRelevance || recency.trim() !== savedRecency

  const save = async () => {
    setSaving(true)
    setError('')
    try {
      const rel = sanitizePatrolKeyword(relevance)
      const rec = sanitizePatrolKeyword(recency)
      await onSave(node.id, rel ? [rel] : [], rec ? [rec] : [])
    } catch (e) {
      setError(e instanceof Error ? e.message : '儲存失敗')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="hx-patrol-node-tags space-y-2 border-t border-line pt-3">
      <p className="text-xs font-bold text-ink-secondary">海巡關鍵字</p>
      <div className="grid gap-2 sm:grid-cols-2">
        <Field label="相關搜尋">
          <Input
            value={relevance}
            onChange={(e) => setRelevance(e.target.value)}
            placeholder="例：化療 沐浴乳"
            className="text-[15px]"
          />
        </Field>
        <Field label="近期求助">
          <Input
            value={recency}
            onChange={(e) => setRecency(e.target.value)}
            placeholder="例：無香沐浴乳 請問"
            className="text-[15px]"
          />
        </Field>
      </div>
      <div className="hx-research-actions hx-research-actions--inline">
        <Button variant="ghost" type="button" onClick={() => void save()} disabled={!dirty || saving}>
          {saving ? '儲存中…' : '儲存此節點'}
        </Button>
        {error ? <span className="text-sm text-danger">{error}</span> : null}
      </div>
    </div>
  )
}