'use client';

import { useQuery } from '@tanstack/react-query';
import { useMemo, useState } from 'react';
import { api } from '@/lib/api';

interface FlatCategory {
  id: number;
  path: string;
}

interface CategoryNode {
  id: number;
  name: string;
  children?: CategoryNode[];
}

function flatten(nodes: CategoryNode[], parentPath = ''): FlatCategory[] {
  const out: FlatCategory[] = [];
  for (const n of nodes) {
    const path = parentPath ? `${parentPath} › ${n.name}` : n.name;
    if (!n.children || n.children.length === 0) {
      out.push({ id: n.id, path });
    } else {
      out.push(...flatten(n.children, path));
    }
  }
  return out;
}

export function CategoryAutocomplete({
  value,
  onChange,
}: {
  value: number | null;
  onChange: (id: number | null) => void;
}) {
  const [query, setQuery] = useState('');
  const [open, setOpen] = useState(false);

  const categoriesQ = useQuery({
    queryKey: ['categories-tree'],
    queryFn: () => api.categories.list(),
    staleTime: 5 * 60_000,
  });

  const flat = useMemo(() => {
    const tree = (categoriesQ.data?.data ?? []) as CategoryNode[];
    return flatten(tree);
  }, [categoriesQ.data]);

  const selectedPath = useMemo(() => flat.find((c) => c.id === value)?.path ?? '', [flat, value]);

  const filtered = useMemo(() => {
    if (!query) return flat.slice(0, 20);
    const q = query.toLowerCase();
    return flat.filter((c) => c.path.toLowerCase().includes(q)).slice(0, 20);
  }, [flat, query]);

  return (
    <div className="relative">
      <input
        value={open ? query : selectedPath}
        placeholder="Search categories…"
        onFocus={() => {
          setOpen(true);
          setQuery('');
        }}
        onBlur={() => setTimeout(() => setOpen(false), 120)}
        onChange={(e) => setQuery(e.target.value)}
        className="w-full rounded border border-forest/20 bg-white px-2 py-1.5 text-sm focus:border-forest focus:outline-none"
      />
      {open && filtered.length > 0 && (
        <ul className="absolute z-10 mt-1 max-h-60 w-full overflow-y-auto rounded border border-forest/20 bg-white shadow">
          {filtered.map((c) => (
            <li key={c.id}>
              <button
                type="button"
                onMouseDown={(e) => {
                  e.preventDefault();
                  onChange(c.id);
                  setOpen(false);
                }}
                className="flex w-full px-2 py-1.5 text-left text-sm hover:bg-bone"
              >
                {c.path}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
