"use client";

import { useCallback } from "react";
import { trpc } from "~/lib/trpc/client.js";
import { EntityCombobox } from "./EntityCombobox.js";

type ResourceItem = { id: string; displayName: string; eid: string };

interface ResourceComboboxProps {
  value: string | null;
  onChange: (id: string | null) => void;
  placeholder?: string;
  disabled?: boolean;
  isActive?: boolean;
  className?: string;
}

export function ResourceCombobox({
  isActive = true,
  ...props
}: ResourceComboboxProps) {
  const useSearchQuery = (search: string, enabled: boolean) => {
    const { data } = trpc.resource.directory.useQuery(
      { search: search || undefined, limit: 15, isActive },
      { enabled, staleTime: 30_000 },
    );
    return { data: (data?.resources ?? []) as ResourceItem[] };
  };

  const useSelectedQuery = (_id: string | null, enabled: boolean) => {
    const { data } = trpc.resource.directory.useQuery(
      { limit: 500 },
      { enabled, staleTime: 60_000 },
    );
    return { data: (data?.resources ?? []) as ResourceItem[] };
  };

  const getLabel = useCallback(
    (r: ResourceItem) => `${r.displayName} (${r.eid})`,
    [],
  );

  const renderItem = useCallback(
    (r: ResourceItem) => (
      <>
        <span>{r.displayName}</span>
        <span className="ml-1.5 text-xs text-gray-400 dark:text-gray-500">{r.eid}</span>
      </>
    ),
    [],
  );

  return (
    <EntityCombobox<ResourceItem>
      {...props}
      placeholder={props.placeholder ?? "Search resource\u2026"}
      useSearchQuery={useSearchQuery}
      useSelectedQuery={useSelectedQuery}
      getLabel={getLabel}
      renderItem={renderItem}
    />
  );
}
