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

import { bookingsService } from '@/services/bookings.service';

interface BookingSelectProps {
  value: string;
  onChange: (bookingId: string) => void;
  label?: string;
  required?: boolean;
  /** Comma-separated statuses to restrict the list (e.g. "PAID" for reservations). */
  statuses?: string;
}

/** Searchable booking picker — shows the human reference (e.g. BKG-BULK-002), submits the UUID. */
export function BookingSelect({ value, onChange, label = 'Booking', required, statuses }: BookingSelectProps) {
  const { data, isLoading } = useQuery({
    queryKey: ['bookings', 'options', statuses ?? 'all'],
    queryFn: () =>
      bookingsService.list({ pageSize: 200, ...(statuses ? { statuses } : {}) }).then((r) => r.items),
  });

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

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