import { useEffect, useRef } from 'react'
import { Search } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Input } from '@/components/ui/Input'
import { useScriptGeneratorStore } from '@/store/scriptGeneratorStore'

interface Props {
  inputValue: string
  setInputValue: (value: string) => void
}

export function ScriptFilterBar({ inputValue, setInputValue }: Props) {
  const categories = useScriptGeneratorStore(s => s.categories)
  const activeCategoryId = useScriptGeneratorStore(s => s.activeCategoryId)
  const setCategory = useScriptGeneratorStore(s => s.setCategory)
  const setSearch = useScriptGeneratorStore(s => s.setSearch)

  // Debounce: 300ms after the input value settles, push to store.
  // Skip on initial mount (store.searchQuery is already '' and page already called loadTemplates).
  const isFirstRender = useRef(true)
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false
      return
    }
    if (debounceRef.current) clearTimeout(debounceRef.current)
    debounceRef.current = setTimeout(() => {
      setSearch(inputValue)
    }, 300)
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current)
    }
  }, [inputValue, setSearch])

  return (
    <div className="flex items-center gap-3 flex-wrap">
      {/* Category pills */}
      <div className="flex items-center gap-1.5 flex-wrap">
        <button
          type="button"
          onClick={() => setCategory(null)}
          className={cn(
            'font-sans text-xs px-3 py-1.5 rounded-full border transition-all',
            activeCategoryId === null
              ? 'bg-primary/10 border-primary/30 text-foreground border-l-[3px] border-l-primary'
              : 'border-border text-muted-foreground hover:border-[rgba(255,255,255,0.12)] hover:text-foreground'
          )}
        >
          All
        </button>
        {categories.map(cat => (
          <button
            key={cat.id}
            type="button"
            onClick={() => setCategory(cat.id)}
            className={cn(
              'font-sans text-xs px-3 py-1.5 rounded-full border transition-all',
              activeCategoryId === cat.id
                ? 'bg-primary/10 border-primary/30 text-foreground border-l-[3px] border-l-primary'
                : 'border-border text-muted-foreground hover:border-[rgba(255,255,255,0.12)] hover:text-foreground'
            )}
          >
            {cat.name}
          </button>
        ))}
      </div>

      {/* Search input */}
      <div className="relative ml-auto">
        <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none z-10" />
        <Input
          type="text"
          value={inputValue}
          onChange={e => setInputValue(e.target.value)}
          placeholder="Search templates..."
          className="pl-8 w-52"
        />
      </div>
    </div>
  )
}
