"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import { Loader2, Package } from "lucide-react";
import { cn, formatCurrency } from "@/lib/utils";

type Product = {
  id: string;
  name: string;
  description: string | null;
  reference: string | null;
  unitPrice: number;
  taxRate: number;
  unit: string | null;
  category: string | null;
};

interface Props {
  value: string;
  onChange: (value: string) => void;
  onSelectProduct: (product: Product) => void;
  placeholder?: string;
  className?: string;
  error?: boolean;
}

export function DescriptionCombobox({
  value,
  onChange,
  onSelectProduct,
  placeholder = "Description du service ou produit",
  className,
  error,
}: Props) {
  const [products, setProducts] = useState<Product[]>([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [activeIndex, setActiveIndex] = useState(-1);
  const containerRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const fetchProducts = useCallback(async (q: string) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({ active: "true" });
      if (q.trim()) params.set("search", q.trim());
      const r = await fetch(`/api/products?${params}`);
      const j = await r.json();
      if (j.success) setProducts(j.data ?? []);
    } catch {
      setProducts([]);
    } finally {
      setLoading(false);
    }
  }, []);

  // Ouvre le dropdown et lance la recherche dès que l'input reçoit le focus
  function handleFocus() {
    setOpen(true);
    setActiveIndex(-1);
    fetchProducts(value);
  }

  // Relance la recherche à chaque frappe (debounce 250ms)
  function handleInput(e: React.ChangeEvent<HTMLInputElement>) {
    const v = e.target.value;
    onChange(v);
    setOpen(true);
    setActiveIndex(-1);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => fetchProducts(v), 250);
  }

  // Navigation clavier
  function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
    if (!open) return;
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setActiveIndex((i) => Math.min(i + 1, products.length - 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActiveIndex((i) => Math.max(i - 1, -1));
    } else if (e.key === "Enter" && activeIndex >= 0) {
      e.preventDefault();
      selectProduct(products[activeIndex]);
    } else if (e.key === "Escape") {
      setOpen(false);
    }
  }

  function selectProduct(p: Product) {
    onSelectProduct(p);
    setOpen(false);
    setProducts([]);
  }

  // Fermer si clic en dehors
  useEffect(() => {
    function onClickOutside(e: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", onClickOutside);
    return () => document.removeEventListener("mousedown", onClickOutside);
  }, []);

  const showDropdown = open && (loading || products.length > 0);

  return (
    <div ref={containerRef} className="relative flex-1">
      <input
        ref={inputRef}
        type="text"
        value={value}
        onChange={handleInput}
        onFocus={handleFocus}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
        autoComplete="off"
        className={cn(
          "flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors",
          "placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
          error && "border-destructive",
          className
        )}
      />

      {/* Dropdown */}
      {showDropdown && (
        <div className="absolute top-full left-0 right-0 z-50 mt-1 max-h-64 overflow-y-auto rounded-md border bg-popover shadow-lg">
          {loading ? (
            <div className="flex items-center justify-center py-4 gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              Recherche…
            </div>
          ) : (
            <>
              {products.length === 0 ? (
                <div className="flex items-center justify-center gap-2 py-4 text-sm text-muted-foreground">
                  <Package className="h-4 w-4 opacity-40" />
                  Aucun produit trouvé
                </div>
              ) : (
                products.map((p, i) => (
                  <button
                    key={p.id}
                    type="button"
                    onMouseDown={(e) => { e.preventDefault(); selectProduct(p); }}
                    onMouseEnter={() => setActiveIndex(i)}
                    className={cn(
                      "w-full flex items-center justify-between gap-3 px-3 py-2.5 text-left text-sm transition-colors",
                      i === activeIndex
                        ? "bg-accent text-accent-foreground"
                        : "hover:bg-accent/60"
                    )}
                  >
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-1.5 flex-wrap">
                        <span className="font-medium truncate">{p.name}</span>
                        {p.reference && (
                          <span className="text-xs text-muted-foreground font-mono shrink-0">
                            {p.reference}
                          </span>
                        )}
                        {p.category && (
                          <span className="text-[10px] rounded-full px-1.5 py-0 bg-muted text-muted-foreground shrink-0">
                            {p.category}
                          </span>
                        )}
                      </div>
                      {p.description && (
                        <p className="text-xs text-muted-foreground truncate mt-0.5">
                          {p.description}
                        </p>
                      )}
                    </div>
                    <div className="text-right shrink-0 ml-2">
                      <p className="text-xs font-semibold text-primary tabular-nums">
                        {formatCurrency(Number(p.unitPrice))}
                      </p>
                      {p.taxRate > 0 && (
                        <p className="text-[10px] text-muted-foreground">
                          TVA {Number(p.taxRate)}%
                        </p>
                      )}
                    </div>
                  </button>
                ))
              )}
            </>
          )}
        </div>
      )}
    </div>
  );
}
