import { useQuery } from "@tanstack/react-query";
import { OperationDatePicker as DatePicker } from "@edr/ui-common";

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

interface OperationDatePickerProps {
  originYardId?: string;
  destinationYardId?: string;
  /** When set, days are cargo-aware: only days whose train can carry THIS booking's cargo type. */
  bookingId?: string;
  value: string;
  onChange: (date: string) => void;
}

/**
 * Route-based day picker for the operation-request step: a thin query wrapper
 * around the shared presentational `OperationDatePicker` from `@edr/ui-common`.
 * Only days with an OPEN scheduled departure on the route are selectable; with
 * a `bookingId` the server additionally drops days whose trains have no wagon
 * type that can carry the booking's cargo (no capacity counts are shown).
 */
export function OperationDatePicker({
  originYardId,
  destinationYardId,
  bookingId,
  value,
  onChange,
}: OperationDatePickerProps) {
  const routeDays = useQuery(
    api.bookings.getAvailableDays.queryOptions({
      input: { originYardId, destinationYardId },
      enabled: !bookingId && !!originYardId && !!destinationYardId,
    }),
  );
  const bookingDays = useQuery(
    api.bookings.getAvailableDaysForBooking.queryOptions({
      input: { bookingId: bookingId ?? "" },
      enabled: !!bookingId,
    }),
  );
  const availableDays = bookingId ? bookingDays.data : routeDays.data;
  const isLoading = bookingId ? bookingDays.isLoading : routeDays.isLoading;

  return (
    <DatePicker
      availableDays={availableDays ?? []}
      isLoading={isLoading}
      value={value}
      onChange={onChange}
    />
  );
}

export default OperationDatePicker;
