"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Search } from "lucide-react";

/**
 * Search box for the results page.
 *
 * The topbar submits to `/dashboard/search?q=…`; this mirrors that contract so
 * a reader can refine the query without going back up to the topbar.
 */
export function SearchField({ defaultValue = "" }: { defaultValue?: string }) {
  const router = useRouter();
  const [value, setValue] = React.useState(defaultValue);

  function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    const term = value.trim();
    if (term.length < 2) return;
    router.push(`/dashboard/search?q=${encodeURIComponent(term)}`);
  }

  return (
    <form onSubmit={handleSubmit} role="search">
      <div className="relative max-w-xl">
        <Search
          className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-tertiary"
          aria-hidden="true"
        />
        <input
          type="search"
          value={value}
          onChange={(event) => setValue(event.target.value)}
          placeholder="Cari kursus, pelajaran, tugas, atau proyek…"
          aria-label="Kata kunci pencarian"
          autoFocus
          className="h-10 w-full border border-line bg-sunken pl-9 pr-3 text-sm text-primary placeholder:text-tertiary focus:border-brand-600 focus:bg-surface focus:outline-none focus:ring-1 focus:ring-brand-600/30"
        />
      </div>
    </form>
  );
}
