import { useEffect, useState } from 'react'
import { motion } from 'framer-motion'
import { Star, Check } from '../../lib/icons'
import { usePersonalData } from '../../stores/personal-data-store'

interface Props {
  itemId: string
  /** When true, surfaces a "rewatch?" toggle next to the rewatch counter
   *  so the user can manually flip the most-recent watch flag without
   *  needing to re-play. Useful when they marked it watched outside the
   *  player. */
  showRewatchToggle?: boolean
}

/**
 * "Personal" section on item detail pages: a 1-10 rating, freeform note,
 * and the rewatch tally. All state lives in `usePersonalData` (local).
 *
 * The note input is debounced via local React state so typing doesn't
 * trigger a store write per keystroke.
 */
export default function PersonalSection({ itemId, showRewatchToggle }: Props) {
  const entry = usePersonalData(s => s.entries[itemId])
  const setRating = usePersonalData(s => s.setRating)
  const setNote = usePersonalData(s => s.setNote)
  const recordWatch = usePersonalData(s => s.recordWatch)

  // Local mirror of the note so typing isn't laggy.
  const [localNote, setLocalNote] = useState(entry?.note || '')

  // Sync from store on item change (so navigating to another item swaps
  // notes correctly without leaking state).
  useEffect(() => {
    setLocalNote(entry?.note || '')
  }, [itemId, entry?.note])

  // Debounce writes by 400ms.
  useEffect(() => {
    if (localNote === (entry?.note || '')) return
    const id = setTimeout(() => setNote(itemId, localNote), 400)
    return () => clearTimeout(id)
  }, [localNote, entry?.note, itemId, setNote])

  const rating = entry?.rating ?? 0
  const rewatchCount = entry?.rewatchCount ?? 0
  const lastWasRewatch = entry?.lastWasRewatch ?? false
  const [hoverRating, setHoverRating] = useState(0)
  // Effective fill is the hover preview when hovering, else the saved rating.
  const previewRating = hoverRating || rating

  return (
    <div className="space-y-5">
      <div>
        <p className="text-[10px] uppercase tracking-[0.18em] font-semibold text-text-3 mb-2">
          Your rating
        </p>
        <div
          className="flex items-center gap-1.5 flex-wrap"
          onMouseLeave={() => setHoverRating(0)}
        >
          {Array.from({ length: 10 }).map((_, i) => {
            const n = i + 1
            const on = n <= previewRating
            const isHover = hoverRating > 0
            return (
              <button
                key={n}
                onClick={() => setRating(itemId, rating === n ? 0 : n)}
                onMouseEnter={() => setHoverRating(n)}
                aria-label={`Rate ${n} out of 10`}
                className={`w-8 h-8 grid place-items-center rounded-md transition-all duration-150 focus-ring ${
                  on
                    ? isHover
                      ? 'bg-accent/25 text-accent shadow-[0_0_12px_-4px_rgba(245,182,66,0.6)]'
                      : 'bg-accent/15 text-accent'
                    : 'bg-elevated/40 text-text-4 hover:text-text-2 hover:bg-elevated/70'
                }`}
              >
                <Star size={14} fill={on ? 'currentColor' : 'none'} stroke={on ? 0 : 1.5} />
              </button>
            )
          })}
          <span className="ml-2 text-[12.5px] text-text-3 tabular-nums">
            {previewRating > 0 ? `${previewRating} / 10` : 'Not rated'}
          </span>
          {rating > 0 && (
            <button
              onClick={() => setRating(itemId, 0)}
              className="ml-1 text-[11px] text-text-4 hover:text-text-2 transition focus-ring rounded"
            >
              Clear
            </button>
          )}
        </div>
      </div>

      <div>
        <p className="text-[10px] uppercase tracking-[0.18em] font-semibold text-text-3 mb-2">
          Note
        </p>
        <textarea
          value={localNote}
          onChange={e => setLocalNote(e.target.value)}
          placeholder='Sticky note for this item - "Lent to Alex Mar 2026", "Watched at the cinema", etc.'
          rows={3}
          className="w-full px-3 py-2.5 rounded-md bg-elevated/40 ring-1 ring-border focus:ring-accent/50 outline-none text-[13px] tracking-tight resize-y leading-relaxed text-text-1 placeholder:text-text-4"
        />
      </div>

      <div>
        <p className="text-[10px] uppercase tracking-[0.18em] font-semibold text-text-3 mb-2">
          Rewatches
        </p>
        <div className="flex items-center gap-3 flex-wrap">
          <motion.span
            key={rewatchCount}
            initial={{ scale: 0.8 }}
            animate={{ scale: 1 }}
            transition={{ duration: 0.25, ease: [0.16, 1, 0.3, 1] }}
            className="inline-flex items-center gap-1.5 h-8 px-3 rounded-full bg-accent/8 ring-1 ring-accent/20 text-[12.5px] text-accent font-medium tracking-tight"
          >
            <span className="tabular-nums font-semibold">{rewatchCount}</span>
            {rewatchCount === 1 ? 'rewatch' : 'rewatches'}
          </motion.span>
          {showRewatchToggle && (
            <button
              onClick={() => recordWatch(itemId, !lastWasRewatch)}
              className={`inline-flex items-center gap-1.5 h-8 px-3 rounded-full text-[11.5px] tracking-tight transition focus-ring ${
                lastWasRewatch
                  ? 'bg-accent text-void'
                  : 'bg-elevated/40 ring-1 ring-border text-text-2 hover:text-text-1'
              }`}
            >
              {lastWasRewatch ? <Check size={11} stroke={2.5} /> : null}
              {lastWasRewatch ? 'Last watch was a rewatch' : 'Mark last watch as rewatch'}
            </button>
          )}
        </div>
      </div>
    </div>
  )
}
