import { useEffect, useRef, useState } from 'react'
import { tagColorVar, type Tag, type TagColor } from '../../api/client'

const COLORS: TagColor[] = ['rose', 'mint', 'peach', 'lavender', 'sky', 'honey']

interface Props {
  roster: Tag[]
  assignedIds: Set<string>
  onToggle: (tag: Tag) => void
  onCreate: (name: string, color: TagColor) => void
  onClose: () => void
}

// TagPicker is the small popover for managing one document's tags: tap an
// existing tag to attach/detach it, or type a new name (with a color swatch) to
// create-and-attach. Closes on outside click or Escape.
export function TagPicker({ roster, assignedIds, onToggle, onCreate, onClose }: Props) {
  const [name, setName] = useState('')
  const [color, setColor] = useState<TagColor>('rose')
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const onDown = (e: PointerEvent) => {
      if (!ref.current?.contains(e.target as Node)) onClose()
    }
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    // Defer so the opening click doesn't immediately close it.
    const id = setTimeout(() => document.addEventListener('pointerdown', onDown), 0)
    document.addEventListener('keydown', onKey)
    return () => {
      clearTimeout(id)
      document.removeEventListener('pointerdown', onDown)
      document.removeEventListener('keydown', onKey)
    }
  }, [onClose])

  const submit = () => {
    const n = name.trim()
    if (!n) return
    onCreate(n, color)
    setName('')
  }

  return (
    <div
      ref={ref}
      onClick={(e) => e.stopPropagation()}
      className="petal-tag-picker absolute z-20 flex w-60 flex-col gap-2 p-3"
      style={{
        top: 'calc(100% + 4px)',
        right: 0,
        borderRadius: 'var(--radius-card)',
        background: 'var(--color-surface)',
        boxShadow: 'var(--shadow-soft)',
        border: '1px solid var(--color-border)',
      }}
    >
      <div className="text-xs font-bold" style={{ color: 'var(--color-muted)' }}>
        标签 · Tags
      </div>

      {roster.length > 0 && (
        <div className="flex max-h-40 flex-wrap gap-1.5 overflow-y-auto">
          {roster.map((t) => {
            const on = assignedIds.has(t.id)
            const c = tagColorVar(t.color)
            return (
              <button
                key={t.id}
                type="button"
                onClick={() => onToggle(t)}
                className="petal-tap inline-flex items-center gap-1 whitespace-nowrap text-xs font-bold"
                style={{
                  borderRadius: 'var(--radius-pill)',
                  padding: '0.25rem 0.6rem',
                  background: on ? c : 'color-mix(in srgb, ' + c + ' 18%, white)',
                  color: on ? 'white' : 'var(--color-plum)',
                  border: `1px solid ${on ? c : 'color-mix(in srgb, ' + c + ' 40%, white)'}`,
                }}
              >
                {on && <span aria-hidden>✓</span>}
                {t.name}
              </button>
            )
          })}
        </div>
      )}

      <div className="flex flex-col gap-1.5 pt-1" style={{ borderTop: '1px solid var(--color-border)' }}>
        <div className="flex items-center gap-1.5">
          {COLORS.map((c) => (
            <button
              key={c}
              type="button"
              aria-label={`Color ${c}`}
              onClick={() => setColor(c)}
              className="petal-tap-sm"
              style={{
                width: 18,
                height: 18,
                borderRadius: 'var(--radius-pill)',
                background: tagColorVar(c),
                border: color === c ? '2px solid var(--color-plum)' : '2px solid transparent',
              }}
            />
          ))}
        </div>
        <div className="flex items-center gap-1.5">
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') submit()
            }}
            placeholder="新标签 · New tag"
            aria-label="New tag name"
            className="petal-tap min-w-0 flex-1 bg-transparent px-2.5 text-sm focus:outline-none"
            style={{
              height: 34,
              borderRadius: 'var(--radius-input)',
              border: '1px solid var(--color-border)',
              color: 'var(--color-plum)',
            }}
          />
          <button
            type="button"
            onClick={submit}
            className="petal-tap-sm shrink-0 px-3 text-sm font-bold text-white"
            style={{ height: 34, borderRadius: 'var(--radius-pill)', background: 'var(--color-accent)' }}
          >
            ＋
          </button>
        </div>
      </div>
    </div>
  )
}
