/**
 * Supplier picker for the Create PO page.
 *
 * Reuses the existing ComboboxField from product-editor (the canonical
 * combobox in this app). Loads the supplier list once via react-query
 * using the shared `["field-options"]` queryKey, so the cache is shared
 * with any other page that reads the same field options and the
 * suppliers list will already be warm if visited elsewhere first.
 */

import { useQuery } from "@tanstack/react-query";
import { apiFetch } from '@/utils/api';
import { ComboboxField } from "@/components/product-editor/ComboboxField";
import { Skeleton } from "@/components/ui/skeleton";
import type { FieldOption } from "@/components/product-editor/types";

interface FieldOptionsResponse {
  suppliers?: FieldOption[];
}

export function SupplierSelector({
  value,
  onChange,
  disabled,
}: {
  /** The selected supplier ID as a string (matches FieldOption.value type). */
  value: string | undefined;
  onChange: (supplierId: string | undefined) => void;
  disabled?: boolean;
}) {
  const { data, isLoading, error } = useQuery({
    queryKey: ["field-options"],
    queryFn: async (): Promise<FieldOptionsResponse> => {
      const res = await apiFetch("/api/import/field-options");
      if (!res.ok) throw new Error("Failed to load suppliers");
      return res.json();
    },
    staleTime: 30 * 60 * 1000, // 30 min — matches the server-side cache TTL
  });

  const options = data?.suppliers ?? [];

  if (isLoading) {
    return <Skeleton className="h-9 w-full" />;
  }

  if (error) {
    return (
      <div className="text-sm text-destructive">
        Failed to load suppliers. Try refreshing the page.
      </div>
    );
  }

  return (
    <ComboboxField
      options={options}
      value={value ?? ""}
      onChange={(v) => onChange(v || undefined)}
      placeholder="Select a supplier…"
      searchPlaceholder="Search suppliers…"
      disabled={disabled}
    />
  );
}
