import { Alert, Loader, Text } from "@mantine/core";
import { AlertCircle, CheckCircle2, Info } from "lucide-react";
import { useQuery } from "@tanstack/react-query";

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

interface DayAvailabilityHintProps {
  bookingId: string;
  /** yyyy-MM-dd (or ISO) — the day the customer has picked. */
  date: string;
  /** EXPORT never splits: a shortfall means the whole booking must move. */
  tradeDirection: "IMPORT" | "EXPORT";
}

/**
 * Advisory free-wagon count for the selected shipment day. It never blocks —
 * the real authorities are the batch engine (import) and the request-operation
 * gate (export). This is a planning nudge so the customer knows, before they
 * proceed, whether the day has room and whether a split/rejection is likely.
 *
 *  - EXPORT: a shortfall is a hard problem (no split) — proceeding will be
 *    rejected — so we warn in red and quote the largest single-train leftover.
 *  - IMPORT/DOMESTIC: a shortfall just means the batch may split the booking or
 *    defer a remainder to a later window — an amber heads-up, not a blocker.
 */
export function DayAvailabilityHint({
  bookingId,
  date,
  tradeDirection,
}: DayAvailabilityHintProps) {
  const { data, isLoading, isError } = useQuery({
    ...api.bookings.getDayAvailability.queryOptions({
      input: { bookingId, date },
      enabled: Boolean(bookingId && date),
    }),
  });

  if (!date) return null;
  if (isLoading) {
    return (
      <Text fz="12px" c="dimmed" mt="xs">
        <Loader size={11} mr={6} style={{ verticalAlign: "middle" }} />
        Checking wagon availability for this day…
      </Text>
    );
  }
  // The advisory is best-effort; if it fails the customer can still proceed and
  // the server-side gate stays authoritative, so we simply show nothing.
  if (isError || !data) return null;

  if (!data.trainsForDay) {
    return (
      <Alert color="gray" radius="md" icon={<Info size={15} />} mt="xs" p="xs">
        <Text fz="12px">
          No departure on this day carries your route — pick another day.
        </Text>
      </Alert>
    );
  }

  if (data.fits) {
    return (
      <Text fz="12px" c="teal" mt="xs">
        <CheckCircle2 size={13} style={{ verticalAlign: "middle" }} />{" "}
        {data.freeWagons} wagon{data.freeWagons === 1 ? "" : "s"} available on
        this day — your booking fits.
      </Text>
    );
  }

  // Shortfall.
  if (tradeDirection === "EXPORT") {
    return (
      <Alert color="red" radius="md" icon={<AlertCircle size={15} />} mt="xs" p="xs">
        <Text fz="12px">
          Not enough space on this day. An export booking must ride one train
          whole, so it can't be split — the largest train still has room for
          about {data.freeWagons} wagon{data.freeWagons === 1 ? "" : "s"}.
          Reduce the booking or pick another day.
        </Text>
      </Alert>
    );
  }

  return (
    <Alert color="yellow" radius="md" icon={<AlertCircle size={15} />} mt="xs" p="xs">
      <Text fz="12px">
        About {data.freeWagons} wagon{data.freeWagons === 1 ? "" : "s"} are free
        on this day — less than your booking needs. You can still proceed: the
        operations team will load what fits and the rest returns for you to
        rebook on a later day.
      </Text>
    </Alert>
  );
}
