import { useState, startTransition } from 'react'
import { Filter } from '../../../lib/icons'
import { useLibraryItems } from '../../../hooks/use-jellyfin'
import ContentRow from '../../../components/ui/ContentRow'
import SmartShelfRow from '../../../components/ui/SmartShelfRow'
import SmartShelfWizard from '../../../components/ui/SmartShelfWizard'
import LazyMount from '../../../components/ui/LazyMount'
import { useSmartShelves } from '../../../stores/smart-shelves-store'
import { usePreferencesStore } from '../../../stores/preferences-store'
import {
  BecauseYouWatchedRow,
  HiddenGemsRow,
  PersonSpotlights,
  TimeOfDayRow,
  UntouchedRow,
  WatchlistRow,
} from './library'
import {
  AwardWinnersMissingRow,
  ComingSoonRow,
  CriticallyAcclaimedMissingRow,
  CultClassicsRow,
  DocumentaryPicksRow,
  ForeignCinemaRow,
  GenreDeepDiveRow,
  TrendingTodayRow,
  YearEndBestOfRow,
} from './discovery'
import {
  DiscoverCanonSection,
  LetterboxdListsSection,
  NetworkRows,
  StudioRows,
} from './brands'

/**
 * Renders all the configurable home-page sections in order, gating each on
 * its individual pref. Keeps the JSX tree at the top of HomePage tidy while
 * letting users hide whatever they don't want via Settings.
 */
export function HomeSections() {
  const prefs = usePreferencesStore()
  // Each row gets wrapped in LazyMount so we don't fire 25+ data queries +
  // 400+ poster cards on first paint. The watchlist row stays eager - it's
  // typically the first thing below the fold and users want it instant.
  return (
    <>
      {prefs.home.show.watchlist && <WatchlistRow />}
      {prefs.home.show.becauseYouWatched && <LazyMount><BecauseYouWatchedRow /></LazyMount>}
      {prefs.home.show.personSpotlights && <LazyMount><PersonSpotlights /></LazyMount>}
      {prefs.home.show.trendingToday && <LazyMount><TrendingTodayRow /></LazyMount>}
      {prefs.home.show.criticallyAcclaimed && <LazyMount><CriticallyAcclaimedMissingRow /></LazyMount>}
      {prefs.home.show.genreDeepDive && <LazyMount><GenreDeepDiveRow /></LazyMount>}
      {prefs.home.show.cultClassics && <LazyMount><CultClassicsRow /></LazyMount>}
      {prefs.home.show.yearEndBestOf && <LazyMount><YearEndBestOfRow /></LazyMount>}
      {prefs.home.show.foreignCinema && <LazyMount><ForeignCinemaRow /></LazyMount>}
      {prefs.home.show.documentaryPicks && <LazyMount><DocumentaryPicksRow /></LazyMount>}
      {prefs.home.show.awardWinnersMissing && <LazyMount><AwardWinnersMissingRow /></LazyMount>}
      {prefs.home.show.studios && <LazyMount><StudioRows /></LazyMount>}
      {prefs.home.show.networks && <LazyMount><NetworkRows /></LazyMount>}
      {prefs.home.show.discoverCanon && <LazyMount><DiscoverCanonSection /></LazyMount>}
      {prefs.home.show.letterboxdLists && <LazyMount><LetterboxdListsSection /></LazyMount>}
      {prefs.home.show.comingSoon && <LazyMount><ComingSoonRow /></LazyMount>}
      {prefs.home.show.moodPicker && <LazyMount><MoodSection /></LazyMount>}
      {prefs.home.show.smartShelves && <LazyMount><SmartShelvesSection /></LazyMount>}
      {prefs.home.show.timeOfDay && <LazyMount><TimeOfDayRow /></LazyMount>}
      {prefs.home.show.untouched && <LazyMount><UntouchedRow /></LazyMount>}
      {prefs.home.show.hiddenGems && <LazyMount><HiddenGemsRow /></LazyMount>}
    </>
  )
}

/**
 * Mood selector. The picker drives a single dynamic row beneath it. Selection
 * is persisted to localStorage so the user lands on their last mood.
 */
const MOODS: Array<{ key: string; label: string; genres: string[] }> = [
  { key: 'cozy', label: 'Cozy', genres: ['Family', 'Animation', 'Comedy'] },
  { key: 'mind-bending', label: 'Mind-bending', genres: ['Mystery', 'Science Fiction', 'Thriller'] },
  { key: 'light', label: 'Light', genres: ['Comedy', 'Family', 'Animation'] },
  { key: 'heavy', label: 'Heavy', genres: ['Drama', 'War', 'History'] },
  { key: 'funny', label: 'Funny', genres: ['Comedy'] },
  { key: 'tense', label: 'Tense', genres: ['Thriller', 'Horror', 'Crime'] },
]

function MoodSection() {
  const [active, setActive] = useState<string | null>(() => {
    if (typeof window === 'undefined') return null
    return localStorage.getItem('home_mood')
  })
  const mood = MOODS.find(m => m.key === active) || null
  const { data } = useLibraryItems(undefined, {
    includeItemTypes: ['Movie', 'Series'],
    genres: mood?.genres,
    sortBy: ['Random'],
    sortOrder: ['Descending'],
    limit: 16,
    enabled: !!mood,
  })
  function pick(key: string) {
    const next = active === key ? null : key
    startTransition(() => setActive(next))
    try {
      if (next) localStorage.setItem('home_mood', next)
      else localStorage.removeItem('home_mood')
    } catch { /* noop */ }
  }
  return (
    <section className="mb-10 px-7">
      <div className="mb-3.5">
        <h2 className="text-[18px] font-semibold text-text-1 tracking-tight">What's your mood?</h2>
        <p className="text-[12px] text-text-3 mt-0.5">Tap one to refresh the row below</p>
      </div>
      <div className="flex flex-wrap gap-1.5 mb-5">
        {MOODS.map(m => {
          const on = active === m.key
          return (
            <button
              key={m.key}
              onClick={() => pick(m.key)}
              className={`h-8 px-3.5 rounded-full text-[12px] font-medium tracking-tight transition border ${
                on
                  ? 'bg-accent text-void border-accent'
                  : 'bg-elevated/40 text-text-2 border-border hover:border-border-strong'
              }`}
            >
              {m.label}
            </button>
          )
        })}
      </div>
      {mood && data?.Items && data.Items.length > 0 && (
        <div className="-mx-7">
          <ContentRow
            title={`${mood.label} picks`}
            subtitle={mood.genres.join(' · ')}
            items={data.Items}
            layoutKey={`mood_${mood.key}`}
          />
        </div>
      )}
    </section>
  )
}

/**
 * Smart shelves. Renders one ContentRow per saved rule plus a trailing
 * "New smart shelf" affordance.
 */
function SmartShelvesSection() {
  const shelves = useSmartShelves(s => s.shelves)
  const [wizardOpen, setWizardOpen] = useState(false)
  return (
    <>
      {shelves.map(s => (
        <SmartShelfRow key={s.id} rule={s} />
      ))}
      <div className="px-7 mb-10">
        <button
          onClick={() => startTransition(() => setWizardOpen(true))}
          className="inline-flex items-center gap-2 h-9 px-3.5 rounded-full bg-elevated/50 ring-1 ring-border hover:ring-accent/40 hover:text-accent text-[12.5px] text-text-2 tracking-tight transition focus-ring"
        >
          <Filter size={13} />
          {shelves.length === 0 ? 'Create a smart shelf' : 'New smart shelf'}
        </button>
      </div>
      <SmartShelfWizard open={wizardOpen} onClose={() => startTransition(() => setWizardOpen(false))} />
    </>
  )
}
