"use client";

import { useEffect, useRef, useState } from "react";
import { listCustomers } from "@/lib/api";
import type { CustomerListItem } from "@/lib/types";

/**
 * Debounced customer search + select. Reports the chosen customer's id and name
 * upward. Used when creating a policy that isn't started from a customer page.
 */
export function CustomerPicker({
  value,
  valueName,
  onPick,
}: {
  value: string;
  valueName?: string;
  onPick: (id: string, name: string) => void;
}) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<CustomerListItem[]>([]);
  const [open, setOpen] = useState(false);
  const debounce = useRef<ReturnType<typeof setTimeout>>();

  useEffect(() => {
    if (debounce.current) clearTimeout(debounce.current);
    if (query.trim().length < 2) {
      setResults([]);
      return;
    }
    debounce.current = setTimeout(() => {
      listCustomers({ query, pageSize: 8 })
        .then((r) => {
          setResults(r.items);
          setOpen(true);
        })
        .catch(() => setResults([]));
    }, 260);
    return () => {
      if (debounce.current) clearTimeout(debounce.current);
    };
  }, [query]);

  return (
    <div className="picker">
      {value ? (
        <div className="picker-selected">
          <span>{valueName ?? "Cliente seleccionado"}</span>
          <button
            type="button"
            className="btn btn-ghost"
            onClick={() => onPick("", "")}
          >
            Cambiar
          </button>
        </div>
      ) : (
        <>
          <input
            className="input"
            placeholder="Buscar cliente por nombre…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onFocus={() => results.length && setOpen(true)}
          />
          {open && results.length > 0 && (
            <ul className="picker-list">
              {results.map((c) => (
                <li key={c.id}>
                  <button
                    type="button"
                    className="picker-item"
                    onClick={() => {
                      onPick(c.id, c.name);
                      setOpen(false);
                      setQuery("");
                    }}
                  >
                    {c.name}
                    {c.city && <span className="muted"> · {c.city}</span>}
                  </button>
                </li>
              ))}
            </ul>
          )}
        </>
      )}
    </div>
  );
}
