import React, { useMemo, useState } from 'react'

export default function ArtworkTags({ artwork }) {
  const [expanded, setExpanded] = useState(false)

  const tags = useMemo(() => {
    const seen = new Set()
    const contentTypeSeen = new Set()
    const categoryPills = []

    // Add content types (e.g. "Wallpapers") first, then categories, then tags
    for (const category of artwork?.categories || []) {
      const ctSlug = category.content_type_slug
      if (ctSlug && !contentTypeSeen.has(ctSlug)) {
        contentTypeSeen.add(ctSlug)
        const ctName = ctSlug.charAt(0).toUpperCase() + ctSlug.slice(1)
        categoryPills.push({
          key: `ct-${ctSlug}`,
          label: ctName,
          href: `/${ctSlug}`,
          isCategory: true,
        })
      }

      if (category.parent && !seen.has(category.parent.id)) {
        seen.add(category.parent.id)
        categoryPills.push({
          key: `cat-${category.parent.id}`,
          label: category.parent.name,
          href: category.parent.url || `/${category.parent.content_type_slug}/${category.parent.slug}`,
          isCategory: true,
        })
      }
      if (!seen.has(category.id)) {
        seen.add(category.id)
        categoryPills.push({
          key: `cat-${category.id}`,
          label: category.name,
          href: category.url || `/${category.content_type_slug}/${category.slug}`,
          isCategory: true,
        })
      }
    }

    const artworkTags = (artwork?.tags || []).map((tag) => ({
      key: `tag-${tag.id || tag.slug}`,
      label: tag.name,
      href: `/tag/${tag.slug || ''}`,
      isCategory: false,
    }))

    return [...categoryPills, ...artworkTags]
  }, [artwork])

  if (tags.length === 0) return null

  const visible = expanded ? tags : tags.slice(0, 12)

  return (
    <div>
      <h3 className="mb-4 text-xs font-semibold uppercase tracking-widest text-accent/70">Tags &amp; Categories</h3>
      <div className="flex flex-wrap gap-2">
        {visible.map((tag, idx) => (
          <a
            key={tag.key}
            href={tag.href}
            className={[
              'inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-xs font-medium transition-all duration-200',
              tag.isCategory
                ? 'border-accent/30 bg-accent/10 text-accent hover:border-accent/50 hover:bg-accent/20'
                : 'border-white/[0.08] bg-white/[0.03] text-white/60 hover:border-white/[0.15] hover:bg-white/[0.06] hover:text-white/80',
            ].join(' ')}
          >
            {tag.label}
          </a>
        ))}

        {tags.length > 12 && (
          <button
            type="button"
            className="inline-flex items-center rounded-full border border-dashed border-white/[0.1] px-3 py-1.5 text-xs text-white/40 transition hover:border-white/20 hover:text-white/60"
            onClick={() => setExpanded((value) => !value)}
          >
            {expanded ? 'Show less' : `+${tags.length - 12} more`}
          </button>
        )}
      </div>
    </div>
  )
}
