import type { CopySuggestedTagData } from '../types/copyMission'
import { Badge, Button } from './ui'

const MAX_TAGS = 6

type CopySuggestedTagsPickerProps = {
  tags: CopySuggestedTagData[]
  selected: string[]
  saving?: boolean
  onChange: (next: string[]) => void
  onSave: () => void
}

export function CopySuggestedTagsPicker({
  tags,
  selected,
  saving,
  onChange,
  onSave,
}: CopySuggestedTagsPickerProps) {
  const selectedSet = new Set(selected)
  const toggle = (tag: string) => {
    if (selectedSet.has(tag)) {
      onChange(selected.filter((item) => item !== tag))
      return
    }
    if (selected.length >= MAX_TAGS) return
    onChange([...selected, tag])
  }

  if (!tags.length) {
    return (
      <p className="text-sm text-ink-secondary">
        尚無建議標籤。先按「產生研究地圖」，系統會預選約 5 個最省配額的搜尋詞。
      </p>
    )
  }

  return (
    <div className="space-y-3">
      <p className="text-sm text-ink-secondary">
        勾選要在 Threads 搜尋的詞（最多 {MAX_TAGS} 個）。只掃你勾的，節省搜尋 API 配額。
      </p>
      <div className="grid gap-2">
        {tags.map((item) => {
          const active = selectedSet.has(item.tag)
          const disabled = !active && selected.length >= MAX_TAGS
          return (
            <button
              key={item.tag}
              type="button"
              onClick={() => toggle(item.tag)}
              disabled={disabled}
              className={`rounded-[var(--radius-md)] border px-4 py-3 text-left transition ${
                active
                  ? 'border-brand bg-brand-soft/40'
                  : 'border-line bg-surface hover:border-brand/40'
              } ${disabled ? 'opacity-50' : ''}`}
              data-islander-label={`標籤 ${item.tag}`}
            >
              <div className="flex flex-wrap items-center gap-2">
                <span className="font-semibold text-ink">{item.tag}</span>
                {item.search_type ? <Badge tone="sky">{item.search_type}</Badge> : null}
                {item.search_intent ? <Badge tone="neutral">{item.search_intent}</Badge> : null}
              </div>
              {item.reason ? <p className="mt-1 text-xs text-ink-secondary">{item.reason}</p> : null}
            </button>
          )
        })}
      </div>
      <div className="flex flex-wrap items-center gap-2">
        <Button variant="soft" onClick={onSave} disabled={saving || selected.length === 0}>
          {saving ? '儲存中…' : `儲存勾選（${selected.length}/${MAX_TAGS}）`}
        </Button>
        <span className="text-xs text-muted">建議 4～5 個即可覆蓋熱門方向</span>
      </div>
    </div>
  )
}