"use client"

import { useState, useEffect } from "react"
import { useQuery } from "convex/react"
import { api } from "../../../../../convex/_generated/api"
import { Input } from "../ui/input"
import { Skeleton } from "../ui/skeleton"
import { HugeiconsIcon } from "@hugeicons/react"
import { Search01Icon, Cancel01Icon } from "@hugeicons/core-free-icons"

interface SearchProduct {
  _id: string
  name: string
}

interface ProductSearchSectionProps {
  onSelect: (product: SearchProduct) => void
  onClear: () => void
  selectedId?: string
}

export function ProductSearchSection({ onSelect, onClear, selectedId }: ProductSearchSectionProps) {
  const [input, setInput] = useState("")
  const [query, setQuery] = useState("")

  useEffect(() => {
    const t = setTimeout(() => setQuery(input), 300)
    return () => clearTimeout(t)
  }, [input])

  const isSearching = query.trim().length > 0

  const results = useQuery(
    api.products.search,
    isSearching ? { query, limit: 3 } : "skip",
  )

  const isLoading = isSearching && results === undefined

  return (
    <div className="space-y-2">
      <div className="relative max-w-sm">
        <HugeiconsIcon
          icon={Search01Icon}
          strokeWidth={2}
          className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
        />
        <Input
          placeholder="Search products…"
          value={input}
          onChange={(e) => {
            setInput(e.target.value)
            if (e.target.value === "") onClear()
          }}
          className="pl-8 pr-8"
        />
        {input && (
          <button
            type="button"
            className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
            onClick={() => {
              setInput("")
              setQuery("")
              onClear()
            }}
            aria-label="Clear search"
          >
            <HugeiconsIcon icon={Cancel01Icon} strokeWidth={2} className="size-4" />
          </button>
        )}
      </div>

      {isLoading && (
        <div className="max-w-sm space-y-1">
          {[0, 1, 2].map((i) => (
            <Skeleton key={i} className="h-9 w-full rounded-md" />
          ))}
        </div>
      )}

      {!isLoading && isSearching && results && results.length === 0 && (
        <p className="text-sm text-muted-foreground">No products match &ldquo;{query}&rdquo;.</p>
      )}

      {!isLoading && results && results.length > 0 && (
        <ul className="max-w-sm divide-y rounded-md border">
          {results.map((product: { _id: string; name: string }) => (
            <li key={product._id}>
              <button
                type="button"
                onClick={() => onSelect({ _id: product._id, name: product.name })}
                className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted ${
                  selectedId === product._id ? "bg-muted font-medium" : ""
                }`}
              >
                {product.name}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}
