import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Button, Group, Select, Text } from "@mantine/core";
import { MapPin } from "lucide-react";

import { api } from "@/services/api";
import { useAssignStation } from "@/hooks/contracts/useContracts";
import { ActionShell } from "./ActionShell";

/**
 * Routes the shipment to an origin station (GL US-02). Binding a staff user is
 * optional here — the station manager can assign one later.
 */
export function AssignStationCard({ bookingId }: { bookingId: string }) {
  const { data: yards = [] } = useQuery(api.routes.yards.queryOptions());
  const assign = useAssignStation(bookingId);
  const [stationYardId, setStationYardId] = useState<string | null>(null);

  return (
    <ActionShell
      icon={MapPin}
      title="Station routing"
      subtitle="Route this shipment to the handling station."
    >
      <Group align="flex-end" wrap="nowrap" gap="sm">
        <Select
          flex={1}
          label="Station"
          placeholder="Select station"
          searchable
          data={yards.map((y) => ({ value: y.id, label: y.label }))}
          value={stationYardId}
          onChange={setStationYardId}
          size="sm"
        />
        <Button
          size="compact-sm"
          color="edr-green"
          loading={assign.isPending}
          disabled={!stationYardId}
          onClick={() =>
            stationYardId && assign.mutate({ stationYardId })
          }
        >
          Route
        </Button>
      </Group>
      <Text size="xs" c="dimmed" mt={6}>
        The shipment moves to the selected station's queue.
      </Text>
    </ActionShell>
  );
}
