import { Select } from '@mantine/core';
import { useQuery } from '@tanstack/react-query';

import { api } from '@/services/api';

interface WagonSelectProps {
  value: string;
  onChange: (wagonId: string) => void;
  label?: string;
  required?: boolean;
}

/** Searchable wagon picker. Lists wagons that are loadable (read-only from scheduling). */
export function WagonSelect({ value, onChange, label = 'Wagon', required }: WagonSelectProps) {
  const { data, isLoading } = useQuery(
    api.warehouses.loadableWagons.queryOptions(),
  );

  const options = (data ?? []).map((w) => ({
    value: w.id,
    label: `${w.wagonNumber} · ${w.status}`,
  }));

  return (
    <Select
      label={label}
      required={required}
      searchable
      clearable
      data={options}
      value={value || null}
      onChange={(v) => onChange(v ?? '')}
      placeholder={isLoading ? 'Loading wagons…' : 'Search wagon number'}
      nothingFoundMessage="No loadable wagons found"
    />
  );
}
