"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";
import { Input } from "../ui/input";
import { Search } from "lucide-react";
import { Button } from "../ui/button";
import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";

export default function SearchBar() {
  const router = useRouter();
  const searchParams = useSearchParams();
  
  // Use local state to track the input instead of updating URL on every keystroke
  const [value, setValue] = useState(searchParams.get("q") ?? "");

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault(); // Prevent full page reload
    
    const params = new URLSearchParams(searchParams.toString());
    
    if (value.trim()) {
      params.set("q", value.trim());
    } else {
      params.delete("q");
    }
    
    // Update the URL only when the form is submitted
    router.replace(`?${params.toString()}`, { scroll: false });
  };

  return (
    <form 
      onSubmit={handleSubmit} 
      className="relative flex items-center mt-10 w-full max-w-2xl px-4 sm:px-0"
    >
      {/* Search Icon */}
      <div className="absolute left-8 sm:left-4 text-muted pointer-events-none flex items-center transition-colors duration-200 peer-focus:text-accent">
        <Search className="text-primary" size={20} />
      </div>

      <Input
        className="
          peer w-full border border-border text-primary
          font-mono font-light text-[0.95rem] tracking-wide
          pl-12 pr-28 py-6 rounded-lg
          placeholder:text-muted-primary
          outline-none transition-all duration-200
          bg-accent
          focus:border-muted focus:shadow-accent
        "
        placeholder="Search books..."
        value={value}
        onChange={(e) => setValue(e.target.value)}
        autoComplete="off"
        spellCheck={false}
      />
      
      {/* Submit Button positioned absolutely inside the input wrapper */}
      <div className="absolute right-6 sm:right-2 flex items-center">
        <Button 
          type="submit" 
          size="sm" 
          className="h-9 px-4 uppercase tracking-wider font-semibold text-xs"
        >
          Search
        </Button>
      </div>
    </form>
  );
}