"use client"

import type React from "react"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Search, Settings2 } from "lucide-react"
import { Input } from "@/components/ui/input"
import type { KeyboardEvent } from "react"

interface SearchBarProps {
  value?: string
  onChange?: (value: string) => void
  placeholder?: string
}

export function SearchBar({ value, onChange, placeholder = "Trouver votre musique..." }: SearchBarProps) {
  const router = useRouter()
  const [localValue, setLocalValue] = useState(value || "")

  const handleChange = (newValue: string) => {
    setLocalValue(newValue)
    onChange?.(newValue)
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (localValue.trim()) {
      router.push(`/search/results?q=${encodeURIComponent(localValue.trim())}`)
    }
  }

  const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter" && localValue && onChange) {
      onChange(localValue)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="relative flex items-center gap-2">
      <div className="relative flex-1">
        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        <Input
          type="text"
          value={localValue}
          onChange={(e) => handleChange(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
          className="h-11 border-0 bg-secondary pl-10 text-foreground placeholder:text-muted-foreground"
        />
      </div>
      <button
        type="button"
        className="flex h-11 w-11 items-center justify-center rounded-lg bg-secondary text-muted-foreground hover:text-foreground"
      >
        <Settings2 className="h-5 w-5" />
      </button>
    </form>
  )
}
