import { useMemo } from 'react'
import { useLibraryItems } from '../../hooks/use-jellyfin'
import ContentRow from './ContentRow'
import { Trash2 } from '../../lib/icons'
import { useSmartShelves, type SmartShelfRule } from '../../stores/smart-shelves-store'

interface Props {
  rule: SmartShelfRule
}

/**
 * Renders a single rule-based shelf on the home page. Translates the
 * rule into Jellyfin /Items query params and pipes the result into
 * ContentRow. The header carries a small delete button so the user can
 * dismiss a shelf they no longer want.
 */
export default function SmartShelfRow({ rule }: Props) {
  const remove = useSmartShelves(s => s.remove)

  const years = useMemo(() => {
    if (rule.yearMin == null && rule.yearMax == null) return undefined
    const lo = rule.yearMin ?? 1900
    const hi = rule.yearMax ?? new Date().getFullYear()
    if (hi < lo) return [lo]
    const out: number[] = []
    for (let y = lo; y <= hi; y++) out.push(y)
    return out
  }, [rule.yearMin, rule.yearMax])

  const sortBy =
    rule.sortBy === 'random' ? ['Random']
    : rule.sortBy === 'recent' ? ['DateCreated']
    : rule.sortBy === 'rating' ? ['CommunityRating']
    : ['SortName']

  const sortOrder = rule.sortBy === 'name' ? ['Ascending'] : ['Descending']

  const filters: string[] | undefined =
    rule.watched === 'played' ? ['IsPlayed']
    : rule.watched === 'unplayed' ? ['IsUnplayed']
    : undefined

  const includeItemTypes =
    rule.type === 'movie' ? ['Movie']
    : rule.type === 'series' ? ['Series']
    : ['Movie', 'Series']

  const { data } = useLibraryItems(undefined, {
    includeItemTypes,
    genres: rule.genres.length > 0 ? rule.genres : undefined,
    years,
    minCommunityRating: rule.minRating,
    filters,
    sortBy,
    sortOrder,
    limit: rule.limit,
  })

  const items = data?.Items || []
  if (items.length === 0) return null

  return (
    <div className="relative group/shelf">
      <ContentRow
        title={rule.name}
        subtitle={describeRule(rule)}
        items={items}
        layoutKey={`smart_${rule.id}`}
      />
      <button
        onClick={() => {
          if (confirm(`Remove the "${rule.name}" smart shelf?`)) remove(rule.id)
        }}
        title="Remove this shelf"
        className="absolute top-3 right-7 w-8 h-8 grid place-items-center rounded-full text-text-3 hover:text-red-300 hover:bg-elevated/80 opacity-0 group-hover/shelf:opacity-100 transition focus-ring"
      >
        <Trash2 size={13} stroke={2} />
      </button>
    </div>
  )
}

function describeRule(rule: SmartShelfRule): string {
  const parts: string[] = []
  if (rule.type === 'movie') parts.push('Movies')
  else if (rule.type === 'series') parts.push('Series')
  if (rule.genres.length > 0) parts.push(rule.genres.slice(0, 3).join(', '))
  if (rule.yearMin != null || rule.yearMax != null) {
    parts.push(`${rule.yearMin ?? '...'}-${rule.yearMax ?? '...'}`)
  }
  if (rule.watched === 'unplayed') parts.push('unwatched')
  else if (rule.watched === 'played') parts.push('watched')
  if (rule.minRating) parts.push(`rating ≥ ${rule.minRating}`)
  return parts.join(' · ')
}
