import { useRef, useState, type KeyboardEvent } from "react"
import { X } from "lucide-react"

interface Props {
  value: string[]
  onChange: (next: string[]) => void
  placeholder?: string
  suggestions?: string[]
  maxLength?: number
}

export default function TagInput({
  value,
  onChange,
  placeholder = "回车 / 逗号添加标签...",
  suggestions = [],
  maxLength = 16,
}: Props) {
  const [draft, setDraft] = useState("")
  const inputRef = useRef<HTMLInputElement>(null)

  const commit = (raw: string) => {
    const tag = raw.trim().replace(/^[,，]+|[,，]+$/g, "").trim()
    if (!tag) return
    if (tag.length > maxLength) return
    if (value.includes(tag)) {
      setDraft("")
      return
    }
    onChange([...value, tag])
    setDraft("")
  }

  const removeAt = (idx: number) => {
    onChange(value.filter((_, i) => i !== idx))
  }

  const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter" || e.key === ",") {
      e.preventDefault()
      commit(draft)
    } else if (e.key === "Backspace" && draft === "" && value.length > 0) {
      removeAt(value.length - 1)
    }
  }

  const remainSuggestions = suggestions.filter((s) => !value.includes(s))

  return (
    <div className="space-y-2">
      <div
        className="flex min-h-10 w-full flex-wrap items-center gap-1.5 rounded-xl border border-slate-200 bg-white px-2 py-1.5 transition-all focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100"
        onClick={() => inputRef.current?.focus()}
      >
        {value.map((tag, idx) => (
          <span
            key={`${tag}-${idx}`}
            className="inline-flex items-center gap-1 rounded-md bg-sky-50 px-2 py-0.5 text-xs text-sky-700 ring-1 ring-inset ring-sky-100"
          >
            {tag}
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation()
                removeAt(idx)
              }}
              className="rounded p-0.5 text-sky-400 transition-colors hover:bg-sky-100 hover:text-sky-600"
              title="移除"
            >
              <X className="h-3 w-3" />
            </button>
          </span>
        ))}
        <input
          ref={inputRef}
          type="text"
          value={draft}
          onChange={(e) => {
            const v = e.target.value
            if (v.endsWith(",") || v.endsWith("，")) {
              commit(v.slice(0, -1))
            } else {
              setDraft(v)
            }
          }}
          onKeyDown={onKey}
          onBlur={() => commit(draft)}
          placeholder={value.length === 0 ? placeholder : ""}
          className="min-w-[120px] flex-1 bg-transparent px-1.5 py-1 text-sm text-slate-700 placeholder:text-slate-300 outline-none"
        />
      </div>
      {remainSuggestions.length > 0 && (
        <div className="flex flex-wrap items-center gap-1.5">
          <span className="text-[10px] text-slate-400">建议：</span>
          {remainSuggestions.map((s) => (
            <button
              key={s}
              type="button"
              onClick={() => commit(s)}
              className="rounded-md bg-slate-50 px-2 py-0.5 text-[11px] text-slate-500 ring-1 ring-inset ring-slate-200 transition-colors hover:bg-sky-50 hover:text-sky-600 hover:ring-sky-200"
            >
              + {s}
            </button>
          ))}
        </div>
      )}
    </div>
  )
}

export function parseBadges(raw: string | null | undefined): string[] {
  if (!raw) return []
  const trimmed = raw.trim()
  if (!trimmed) return []
  try {
    const parsed = JSON.parse(trimmed)
    if (Array.isArray(parsed)) {
      return parsed.map((x) => String(x)).filter((s) => s.length > 0)
    }
  } catch {
    // fall through — 兼容老数据：逗号分隔
  }
  return trimmed
    .split(/[,，]/)
    .map((s) => s.trim())
    .filter((s) => s.length > 0)
}

export function stringifyBadges(tags: string[]): string | null {
  if (tags.length === 0) return null
  return JSON.stringify(tags)
}
