import { useEffect, useMemo, useState } from 'react';
import {
Alert,
Badge,
Button,
Checkbox,
Group,
Loader,
Modal,
NumberInput,
Select,
Stack,
Table,
Tabs,
Text,
Textarea,
TextInput,
} from '@mantine/core';
import { Info, PackageSearch, Truck } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import {
useBulkReceive,
useEligibleBookings,
useLoadPassedExport,
useReceiveInventory,
useWarehouseYards,
useWarehouseZones,
useWarehouses,
} from '@/hooks/useWarehouses';
import type { BulkReceiveResult, LoadPassedExportResult, ReceiveInventoryPayload } from '@/types/warehouse';
import { BookingSelect } from './BookingSelect';
import { extractErrorMessage, formatNumber } from './options';
interface ReceiveInventoryModalProps {
opened: boolean;
onClose: () => void;
/** When supplied the modal locks to a single booking (legacy single-receive). */
bookingId?: string;
bookingLabel?: string;
onReceived?: () => void;
}
interface Location {
warehouseId: string;
yardId: string;
zoneId: string;
}
/** Cascading Warehouse → Yard → Zone selectors (ACTIVE only). */
function LocationSelects({
value,
onChange,
}: {
value: Location;
onChange: (next: Location) => void;
}) {
const warehousesQuery = useWarehouses({ status: 'ACTIVE' });
const yardsQuery = useWarehouseYards(value.warehouseId || undefined);
const zonesQuery = useWarehouseZones(value.yardId || undefined);
const warehouseOptions = useMemo(
() => (warehousesQuery.data ?? []).map((w) => ({ value: w.id, label: `${w.name} (${w.code})` })),
[warehousesQuery.data],
);
const yardOptions = useMemo(
() =>
(yardsQuery.data ?? [])
.filter((y) => y.status === 'ACTIVE')
.map((y) => ({ value: y.id, label: `${y.name} (${y.code})` })),
[yardsQuery.data],
);
const zoneOptions = useMemo(
() =>
(zonesQuery.data ?? [])
.filter((z) => z.status === 'ACTIVE')
.map((z) => ({ value: z.id, label: `${z.name} (${z.code})` })),
[zonesQuery.data],
);
return (
);
}
/** One tab: eligible PAID bookings for a direction, with bulk receive (+ export load). */
function EligibleTab({
direction,
location,
enabled,
onChanged,
}: {
direction: 'IMPORT' | 'EXPORT';
location: Location;
enabled: boolean;
onChanged?: () => void;
}) {
const { toast } = useToast();
const { data: rows = [], isLoading } = useEligibleBookings(direction, enabled);
const bulkReceive = useBulkReceive();
const loadPassed = useLoadPassedExport();
const [selected, setSelected] = useState>(new Set());
const locationReady = Boolean(location.warehouseId && location.yardId && location.zoneId);
const allSelected = rows.length > 0 && selected.size === rows.length;
const someSelected = selected.size > 0 && !allSelected;
const toggleAll = () =>
setSelected(allSelected ? new Set() : new Set(rows.map((r) => r.id)));
const toggleOne = (id: string) =>
setSelected((prev) => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
const receive = async (bookingIds: string[]) => {
if (!locationReady) {
toast({ variant: 'destructive', title: 'Select warehouse, yard and zone first' });
return;
}
if (bookingIds.length === 0) {
toast({ variant: 'destructive', title: 'Select at least one booking' });
return;
}
try {
const res = (await bulkReceive.mutateAsync({ direction, ...location, bookingIds })) as {
data: BulkReceiveResult;
};
const r = res.data;
toast({
title: `${r.receivedCount} received`,
description: r.skippedCount ? `${r.skippedCount} skipped` : undefined,
});
setSelected(new Set());
onChanged?.();
} catch (error) {
toast({ variant: 'destructive', title: 'Receive failed', description: extractErrorMessage(error) });
}
};
const loadPassedExport = async () => {
try {
const res = (await loadPassed.mutateAsync(undefined)) as { data: LoadPassedExportResult };
const r = res.data;
toast({
title: `${r.loadedCount} loaded`,
description: r.skippedCount ? `${r.skippedCount} skipped — inspection not passed` : undefined,
});
onChanged?.();
} catch (error) {
toast({ variant: 'destructive', title: 'Load failed', description: extractErrorMessage(error) });
}
};
return (
Selected: {selected.size} / {rows.length} eligible
{direction === 'EXPORT' && (
}
loading={loadPassed.isPending}
onClick={loadPassedExport}
>
Load Passed Export Items
)}
{!locationReady && (
} color="orange" variant="light">
Select a warehouse, yard and zone above before receiving.
)}
{isLoading ? (
) : rows.length === 0 ? (
No eligible PAID {direction.toLowerCase()} bookings to receive.
) : (
Booking Ref
Booking ID
Customer ID
Customer Name
Origin
Destination
Route
Container #
Cargo Type
Weight
Payment
Current Status
Inspection
Actions
{rows.map((r) => (
toggleOne(r.id)}
/>
{r.reference}
{r.id.slice(0, 8)}…
{r.customerId ? `${r.customerId.slice(0, 8)}…` : '—'}
{r.customer ?? '—'}
{r.origin ?? '—'}
{r.destination ?? '—'}
{r.origin || r.destination ? `${r.origin ?? '?'} → ${r.destination ?? '?'}` : '—'}
—
{r.cargo ?? '—'}
{formatNumber(Number(r.weight))}
{r.paymentStatus}
{r.status ?? '—'}
—
))}
)}
);
}
/** New bulk Receive: Import / Export tabs with eligible PAID bookings. */
function BulkReceiveModal({ opened, onClose, onReceived }: ReceiveInventoryModalProps) {
const [location, setLocation] = useState({ warehouseId: '', yardId: '', zoneId: '' });
const [tab, setTab] = useState<'IMPORT' | 'EXPORT'>('IMPORT');
useEffect(() => {
if (opened) setLocation({ warehouseId: '', yardId: '', zoneId: '' });
}, [opened]);
return (
setTab((v as 'IMPORT' | 'EXPORT') ?? 'IMPORT')}>
}>
Import
}>
Export
Receive Queue
Ready To Load
Loaded
Dispatch Queue
Ready To Load — coming in the next batch.
Loaded — coming in the next batch.
Dispatch Queue — coming in the next batch.
);
}
interface SingleFormState {
warehouseId: string;
yardId: string;
zoneId: string;
quantity: number | '';
weight: number | '';
volume: number | '';
notes: string;
}
/** Legacy single-booking receive — used when a specific bookingId is supplied. */
function SingleBookingReceiveModal({
opened,
onClose,
bookingId,
bookingLabel,
onReceived,
}: ReceiveInventoryModalProps) {
const { toast } = useToast();
const receiveMutation = useReceiveInventory();
const [selectedBooking, setSelectedBooking] = useState(bookingId ?? '');
const [form, setForm] = useState({
warehouseId: '',
yardId: '',
zoneId: '',
quantity: '',
weight: '',
volume: '',
notes: '',
});
useEffect(() => {
if (opened) {
setSelectedBooking(bookingId ?? '');
setForm({ warehouseId: '', yardId: '', zoneId: '', quantity: '', weight: '', volume: '', notes: '' });
}
}, [opened, bookingId]);
const location: Location = { warehouseId: form.warehouseId, yardId: form.yardId, zoneId: form.zoneId };
const handleSubmit = async () => {
if (!selectedBooking.trim()) {
toast({ variant: 'destructive', title: 'Booking is required' });
return;
}
if (!form.warehouseId || !form.yardId || !form.zoneId) {
toast({ variant: 'destructive', title: 'Select warehouse, yard and zone' });
return;
}
if (form.quantity === '' || form.weight === '') {
toast({ variant: 'destructive', title: 'Quantity and weight are required' });
return;
}
const payload: ReceiveInventoryPayload = {
bookingId: selectedBooking.trim(),
warehouseId: form.warehouseId,
yardId: form.yardId,
zoneId: form.zoneId,
quantity: Number(form.quantity),
weight: Number(form.weight),
volume: form.volume === '' ? undefined : Number(form.volume),
notes: form.notes.trim() || undefined,
};
try {
await receiveMutation.mutateAsync(payload);
toast({ title: 'Inventory received' });
onReceived?.();
onClose();
} catch (error) {
toast({ variant: 'destructive', title: 'Receive failed', description: extractErrorMessage(error) });
}
};
return (
{bookingId ? (
) : (
)}
setForm((f) => ({ ...f, ...next }))} />
setForm((f) => ({ ...f, quantity: value === '' ? '' : Number(value) }))}
/>
setForm((f) => ({ ...f, weight: value === '' ? '' : Number(value) }))}
/>
setForm((f) => ({ ...f, volume: value === '' ? '' : Number(value) }))}
/>
);
}
export function ReceiveInventoryModal(props: ReceiveInventoryModalProps) {
// Locked to a booking → legacy single receive; otherwise the Import/Export bulk flow.
return props.bookingId ? : ;
}