"use client"

import React, { useRef, useEffect, useCallback } from "react"
import { Search, X, Command } from "lucide-react"

interface SearchBarProps {
  value: string
  onChange: (value: string) => void
  placeholder?: string
  className?: string
  autoFocus?: boolean
  showKeyboardShortcut?: boolean
}

export function SearchBar({
  value,
  onChange,
  placeholder = "Search tasks...",
  className = "",
  autoFocus = false,
  showKeyboardShortcut = true,
}: SearchBarProps) {
  const inputRef = useRef<HTMLInputElement>(null)

  // Handle Ctrl/Cmd+K keyboard shortcut
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Check for Ctrl+K or Cmd+K
      if ((e.ctrlKey || e.metaKey) && e.key === "k") {
        e.preventDefault()
        inputRef.current?.focus()
      }
      // Check for Escape to clear and blur
      if (e.key === "Escape" && document.activeElement === inputRef.current) {
        if (value) {
          onChange("")
        } else {
          inputRef.current?.blur()
        }
      }
    }

    document.addEventListener("keydown", handleKeyDown)
    return () => document.removeEventListener("keydown", handleKeyDown)
  }, [value, onChange])

  const handleClear = useCallback(() => {
    onChange("")
    inputRef.current?.focus()
  }, [onChange])

  return (
    <div className={`relative ${className}`}>
      <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
      <input
        ref={inputRef}
        type="text"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        autoFocus={autoFocus}
        className="w-full pl-9 pr-20 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white placeholder-slate-500 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-colors"
      />
      
      {/* Right side controls */}
      <div className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1">
        {value && (
          <button
            onClick={handleClear}
            className="p-1 hover:bg-slate-700 rounded text-slate-400 hover:text-white transition-colors"
            title="Clear search"
          >
            <X className="w-3.5 h-3.5" />
          </button>
        )}
        
        {showKeyboardShortcut && !value && (
          <kbd className="hidden sm:flex items-center gap-0.5 px-1.5 py-0.5 text-[10px] font-mono text-slate-500 bg-slate-700/50 rounded border border-slate-600">
            <Command className="w-3 h-3" />
            <span>K</span>
          </kbd>
        )}
      </div>
    </div>
  )
}

export default SearchBar
