import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { X, Filter } from '../../lib/icons'
import { useSmartShelves, type SmartShelfRule } from '../../stores/smart-shelves-store'

interface Props {
  open: boolean
  onClose: () => void
}

const GENRE_CHOICES = [
  'Action', 'Adventure', 'Animation', 'Comedy', 'Crime', 'Documentary', 'Drama',
  'Family', 'Fantasy', 'History', 'Horror', 'Music', 'Mystery', 'Romance',
  'Science Fiction', 'Thriller', 'War', 'Western',
]

/**
 * Lightweight wizard for building a SmartShelfRule. Persists into the
 * shelves store; the home page subscribes and renders one row per shelf.
 *
 * Inputs only what's actionable on the Jellyfin /Items endpoint to avoid
 * client-side filtering surprises - mostly genres, year range, type,
 * watched status, minimum rating, sort.
 */
export default function SmartShelfWizard({ open, onClose }: Props) {
  const add = useSmartShelves(s => s.add)
  const [draft, setDraft] = useState<Omit<SmartShelfRule, 'id' | 'createdAt'>>(emptyDraft())

  function reset() {
    setDraft(emptyDraft())
  }
  function save() {
    if (!draft.name.trim()) return
    add({ ...draft, name: draft.name.trim() })
    reset()
    onClose()
  }
  function toggleGenre(g: string) {
    setDraft(d => ({
      ...d,
      genres: d.genres.includes(g) ? d.genres.filter(x => x !== g) : [...d.genres, g],
    }))
  }

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.18 }}
          onClick={onClose}
          className="fixed inset-0 z-[80] grid place-items-center bg-black/65 backdrop-blur-sm p-6"
          role="dialog"
        >
          <motion.div
            initial={{ y: 24, scale: 0.96 }}
            animate={{ y: 0, scale: 1 }}
            exit={{ y: 24, scale: 0.96 }}
            transition={{ duration: 0.32, ease: [0.16, 1, 0.3, 1] }}
            onClick={e => e.stopPropagation()}
            className="relative w-full max-w-xl rounded-2xl bg-surface ring-1 ring-border-strong shadow-[0_30px_80px_-20px_rgba(0,0,0,0.85)] max-h-[88vh] overflow-y-auto"
          >
            <header className="sticky top-0 z-10 flex items-center justify-between p-5 pb-3 bg-surface/95 backdrop-blur border-b border-border">
              <div className="flex items-center gap-2">
                <Filter size={16} className="text-accent" />
                <h2 className="text-[16px] font-semibold tracking-tight text-text-1">
                  New smart shelf
                </h2>
              </div>
              <button
                onClick={onClose}
                aria-label="Close"
                className="w-8 h-8 grid place-items-center rounded-full text-text-3 hover:text-text-1 hover:bg-elevated transition focus-ring"
              >
                <X size={14} stroke={2} />
              </button>
            </header>

            <div className="p-5 pt-4 space-y-5 text-[13px]">
              <Field label="Name">
                <input
                  type="text"
                  value={draft.name}
                  onChange={e => setDraft(d => ({ ...d, name: e.target.value }))}
                  placeholder='e.g. "Unwatched 4K HDR" or "1980s noir"'
                  className="w-full h-10 px-3 rounded-md bg-elevated/60 ring-1 ring-border focus:ring-accent/50 outline-none text-[13px] tracking-tight"
                />
              </Field>

              <Field label="Type">
                <Segmented
                  value={draft.type}
                  onChange={v => setDraft(d => ({ ...d, type: v }))}
                  options={[
                    { value: 'any', label: 'Any' },
                    { value: 'movie', label: 'Movies' },
                    { value: 'series', label: 'Series' },
                  ]}
                />
              </Field>

              <Field label="Genres" hint="Pick any number; leave empty for any genre">
                <div className="flex flex-wrap gap-1.5">
                  {GENRE_CHOICES.map(g => {
                    const on = draft.genres.includes(g)
                    return (
                      <button
                        key={g}
                        onClick={() => toggleGenre(g)}
                        className={`h-7 px-2.5 rounded-full text-[11.5px] tracking-tight transition border ${
                          on
                            ? 'bg-accent/15 text-accent border-accent/40'
                            : 'bg-elevated/40 text-text-2 border-border hover:border-border-strong'
                        }`}
                      >
                        {g}
                      </button>
                    )
                  })}
                </div>
              </Field>

              <Field label="Year range" hint="Inclusive on both ends">
                <div className="flex items-center gap-2 max-w-xs">
                  <input
                    type="number"
                    value={draft.yearMin ?? ''}
                    onChange={e =>
                      setDraft(d => ({
                        ...d,
                        yearMin: e.target.value ? Number(e.target.value) : undefined,
                      }))
                    }
                    placeholder="From"
                    className="flex-1 h-10 px-3 rounded-md bg-elevated/60 ring-1 ring-border focus:ring-accent/50 outline-none tabular-nums"
                  />
                  <span className="text-text-4">→</span>
                  <input
                    type="number"
                    value={draft.yearMax ?? ''}
                    onChange={e =>
                      setDraft(d => ({
                        ...d,
                        yearMax: e.target.value ? Number(e.target.value) : undefined,
                      }))
                    }
                    placeholder="To"
                    className="flex-1 h-10 px-3 rounded-md bg-elevated/60 ring-1 ring-border focus:ring-accent/50 outline-none tabular-nums"
                  />
                </div>
              </Field>

              <Field label="Watched">
                <Segmented
                  value={draft.watched}
                  onChange={v => setDraft(d => ({ ...d, watched: v }))}
                  options={[
                    { value: 'any', label: 'Any' },
                    { value: 'unplayed', label: 'Unwatched' },
                    { value: 'played', label: 'Watched' },
                  ]}
                />
              </Field>

              <Field label="Minimum rating" hint="Community rating; leave blank for any">
                <input
                  type="number"
                  step="0.1"
                  min="0"
                  max="10"
                  value={draft.minRating ?? ''}
                  onChange={e =>
                    setDraft(d => ({
                      ...d,
                      minRating: e.target.value ? Number(e.target.value) : undefined,
                    }))
                  }
                  placeholder="e.g. 7.5"
                  className="w-32 h-10 px-3 rounded-md bg-elevated/60 ring-1 ring-border focus:ring-accent/50 outline-none tabular-nums"
                />
              </Field>

              <Field label="Sort">
                <Segmented
                  value={draft.sortBy}
                  onChange={v => setDraft(d => ({ ...d, sortBy: v }))}
                  options={[
                    { value: 'random', label: 'Random' },
                    { value: 'recent', label: 'Recent' },
                    { value: 'rating', label: 'Rating' },
                    { value: 'name', label: 'Name' },
                  ]}
                />
              </Field>
            </div>

            <footer className="sticky bottom-0 z-10 flex items-center justify-end gap-2 p-5 pt-3 bg-surface/95 backdrop-blur border-t border-border">
              <button
                onClick={onClose}
                className="h-10 px-4 rounded-full text-[12.5px] text-text-2 hover:text-text-1 hover:bg-elevated transition focus-ring"
              >
                Cancel
              </button>
              <button
                onClick={save}
                disabled={!draft.name.trim()}
                className="h-10 px-5 rounded-full bg-accent text-void text-[12.5px] font-semibold tracking-tight transition disabled:opacity-40 disabled:cursor-not-allowed hover:bg-accent-hover focus-ring"
              >
                Save shelf
              </button>
            </footer>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}

function emptyDraft(): Omit<SmartShelfRule, 'id' | 'createdAt'> {
  return {
    name: '',
    type: 'any',
    genres: [],
    watched: 'any',
    sortBy: 'random',
    limit: 18,
  }
}

function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-[10.5px] uppercase tracking-[0.16em] font-semibold text-text-3 mb-1.5">
        {label}
      </label>
      {children}
      {hint && <p className="text-[11px] text-text-4 mt-1.5 leading-relaxed">{hint}</p>}
    </div>
  )
}

function Segmented<T extends string>({
  value,
  onChange,
  options,
}: {
  value: T
  onChange: (v: T) => void
  options: { value: T; label: string }[]
}) {
  return (
    <div className="inline-flex bg-elevated/40 ring-1 ring-border rounded-md p-0.5">
      {options.map(o => (
        <button
          key={o.value}
          onClick={() => onChange(o.value)}
          className={`h-8 px-3 rounded text-[11.5px] font-medium tracking-tight transition focus-ring ${
            value === o.value ? 'bg-accent text-void' : 'text-text-3 hover:text-text-1'
          }`}
        >
          {o.label}
        </button>
      ))}
    </div>
  )
}
