"use client";

import { useState, useRef, useCallback } from "react";
import { useQuery } from "@tanstack/react-query";
import { Input } from "@/components/ui/input";
import { Search } from "lucide-react";
import { searchTaskTemplates } from "@/lib/api/lookups";
import type { TaskTemplateResponse } from "@/lib/api/lookups";

interface TemplateSearchProps {
  onSelect: (template: TaskTemplateResponse) => void;
  onTitleChange: (title: string) => void;
}

export function TemplateSearch({ onSelect, onTitleChange }: TemplateSearchProps) {
  const [query, setQuery] = useState("");
  const [isFocused, setIsFocused] = useState(false);
  const blurTimeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);

  const { data: results = [] } = useQuery({
    queryKey: ["task-templates", "search", query],
    queryFn: () => searchTaskTemplates(query),
    enabled: query.length >= 2,
  });

  const showDropdown = isFocused && query.length >= 2 && results.length > 0;

  const handleChange = useCallback(
    (value: string) => {
      setQuery(value);
      onTitleChange(value);
    },
    [onTitleChange]
  );

  const handleSelect = useCallback(
    (template: TaskTemplateResponse) => {
      setQuery(template.title);
      onTitleChange(template.title);
      onSelect(template);
      setIsFocused(false);
    },
    [onSelect, onTitleChange]
  );

  const handleFocus = useCallback(() => {
    if (blurTimeoutRef.current) {
      clearTimeout(blurTimeoutRef.current);
    }
    setIsFocused(true);
  }, []);

  const handleBlur = useCallback(() => {
    blurTimeoutRef.current = setTimeout(() => {
      setIsFocused(false);
    }, 200);
  }, []);

  return (
    <div className="relative">
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
        <Input
          value={query}
          onChange={(e) => handleChange(e.target.value)}
          onFocus={handleFocus}
          onBlur={handleBlur}
          placeholder="Search templates or type a title..."
          className="pl-9"
        />
      </div>

      {showDropdown && (
        <div className="absolute z-50 w-full mt-1 rounded-md border bg-popover shadow-lg max-h-60 overflow-y-auto">
          {results.map((template) => (
            <button
              key={template.id}
              type="button"
              className="w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors"
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => handleSelect(template)}
            >
              <div className="font-medium">{template.title}</div>
              {template.description && (
                <div className="text-xs text-muted-foreground truncate">
                  {template.description}
                </div>
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
