"use client";

import { useCallback } from "react";
import { trpc } from "~/lib/trpc/client.js";
import type { ProjectStatus } from "@capakraken/shared";
import { EntityCombobox } from "./EntityCombobox.js";

type ProjectItem = { id: string; shortCode: string; name: string };

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

export function ProjectCombobox({
  status,
  ...props
}: ProjectComboboxProps) {
  const useSearchQuery = (search: string, enabled: boolean) => {
    const { data } = trpc.project.list.useQuery(
      { search: search || undefined, limit: 15, ...(status ? { status } : {}) },
      { enabled, staleTime: 30_000 },
    );
    return { data: (data?.projects ?? []) as ProjectItem[] };
  };

  const useSelectedQuery = (_id: string | null, enabled: boolean) => {
    const { data } = trpc.project.list.useQuery(
      { limit: 500 },
      { enabled, staleTime: 60_000 },
    );
    return { data: (data?.projects ?? []) as ProjectItem[] };
  };

  const getLabel = useCallback(
    (p: ProjectItem) => `${p.shortCode} \u2014 ${p.name}`,
    [],
  );

  const renderItem = useCallback(
    (p: ProjectItem) => (
      <>
        <span className="font-medium text-xs text-gray-400 dark:text-gray-500 mr-1.5">{p.shortCode}</span>
        <span>{p.name}</span>
      </>
    ),
    [],
  );

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