import { Group, Paper, Stack, Text, Divider } from "@mantine/core";
import { useQuery } from "@tanstack/react-query";
import { Warehouse as WarehouseIcon } from "lucide-react";

import { warehouseService } from "@/services/warehouse.service";

interface WarehouseLocationCardProps {
  bookingId: string;
}

function Row({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <Group justify="space-between" wrap="nowrap">
      <Text size="sm" c="dimmed">
        {label}
      </Text>
      <Text size="sm" fw={500} ta="right">
        {value}
      </Text>
    </Group>
  );
}

export function WarehouseLocationCard({ bookingId }: WarehouseLocationCardProps) {
  const { data, isLoading } = useQuery({
    queryKey: ["warehouse-inventory", "booking-location", bookingId],
    queryFn: () => warehouseService.bookingLocation(bookingId),
  });

  const items = data ?? [];
  const latest = items[0];

  return (
    <Paper withBorder radius="md" p="lg">
      <Stack gap="md">
        <Group gap="xs">
          <WarehouseIcon size={18} />
          <Text fw={700}>Warehouse Location</Text>
        </Group>

        <Divider />

        {isLoading ? (
          <Text size="sm" c="dimmed">
            Loading…
          </Text>
        ) : !latest ? (
          <Text size="sm" c="dimmed">
            Your cargo will appear here once it arrives at the warehouse.
          </Text>
        ) : (
          <Stack gap="xs">
            <Row
              label="Warehouse"
              value={latest.warehouse ? `${latest.warehouse.name} (${latest.warehouse.code})` : "—"}
            />
            <Row
              label="Yard"
              value={latest.yard ? `${latest.yard.name} (${latest.yard.code})` : "—"}
            />
            <Row
              label="Zone"
              value={latest.zone ? `${latest.zone.name} (${latest.zone.code})` : "—"}
            />
            <Row label="Arrived At" value={latest.arrivedAt ? new Date(latest.arrivedAt).toLocaleString() : "—"} />
          </Stack>
        )}
      </Stack>
    </Paper>
  );
}
