import { directionLabel } from "@/lib/utils";
import { useCallback, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  ActionIcon,
  Badge,
  Box,
  Button,
  Card,
  Group,
  SegmentedControl,
  Select,
  Stack,
  Text,
  TextInput,
  ThemeIcon,
  Tooltip,
} from "@mantine/core";
import {
  AlertTriangle,
  ArrowRight,
  CalendarClock,
  ChevronRight,
  FileSignature,
  FileText,
  Inbox,
  PackageCheck,
  RefreshCw,
  Search,
  ShieldCheck,
  Ship,
  ShipWheel,
  Truck,
  User,
  Weight,
  X,
} from "lucide-react";
import {
  DataTable,
  DataTableFooter,
  usePagination,
  type ColumnDef,
} from "@edr/ui-common";
import type { Freight } from "@edr/types";

import { PageContainer } from "@/components/page/PageContainer";
import { PageHeader } from "@/components/page/PageHeader";
import { KpiStrip } from "@/components/page/KpiStrip";
import { bookingTable } from "@/components/bookings/booking-ui.styles";
import { useDjClearanceQueue } from "@/hooks/contracts/useContracts";
import { useBookingDjClearanceQueue } from "@/hooks/bookings/useBookings";
import type { BookingDetail } from "@/types/booking";

type QueueTab = "contracts" | "shipments";

const prettyStatus = (s?: string | null) =>
  (s ?? "")
    .toLowerCase()
    .replace(/_/g, " ")
    .replace(/^\w/, (c) => c.toUpperCase());

function formatDate(value?: string | null): string {
  if (!value) return "—";
  const d = new Date(value);
  return Number.isNaN(d.getTime())
    ? "—"
    : d.toLocaleDateString(undefined, {
        year: "numeric",
        month: "short",
        day: "numeric",
      });
}

function yardLabel(
  yard?: { label?: string; code?: string; name?: string } | null,
  fallback = "—",
): string {
  if (!yard) return fallback;
  return yard.label ?? yard.name ?? yard.code ?? fallback;
}

const PHASE_LABELS: Record<string, string> = {
  CUSTOMER_INTAKE: "Customer intake",
  GL_ET_REVIEW: "GL ET review",
  GL_DJ_COLLECTION: "DJ collection",
  GL_ET_OUTPUT: "GL ET output",
  CUSTOMER_DUTY: "Customer duty",
  GL_ET_POST_CLEARANCE: "ET post-clearance",
  GL_DJ_LOADING: "DJ loading",
  POST_TRANSIT: "Post transit",
};

const phaseLabel = (phase?: string | null) =>
  phase ? (PHASE_LABELS[phase] ?? prettyStatus(phase)) : "—";

function statusColor(status: string): string {
  switch (status) {
    case "AWAITING_DOCUMENTS":
    case "AWAITING_CLEARANCE_DOCUMENTS":
      return "yellow";
    case "DOCUMENTS_UNDER_REVIEW":
    case "CLEARANCE_UNDER_REVIEW":
      return "blue";
    case "CLEARANCE_READY":
    case "CLEARANCE_READY_FOR_BOOKING":
      return "edr-green";
    case "ACTIVE_SHIPMENT_IN_PROGRESS":
    case "IN_TRANSIT":
      return "teal";
    // Payment phase — booking selected / awaiting the customer's payment.
    case "SELECTED_FOR_BATCH":
    case "PNR_GENERATED":
    case "AWAITING_PAYMENT":
    case "PAYMENT_VERIFICATION_IN_PROGRESS":
      return "violet";
    // Terminal rows kept as clearance history.
    case "EXPIRED":
      return "orange";
    case "CANCELLED":
    case "REJECTED":
      return "red";
    default:
      return "gray";
  }
}

// ── DJ next action (shipments) ───────────────────────────────────────────────

type DjActionKey = "RO_HOLD" | "COLLECT_DO" | "ISSUE_RO" | "LOADING" | "REVIEW";

interface DjAction {
  key: DjActionKey;
  label: string;
  color: string;
}

const DJ_ACTION_OPTIONS: { value: DjActionKey; label: string }[] = [
  { value: "RO_HOLD", label: "RO amendment hold" },
  { value: "COLLECT_DO", label: "Collect DO" },
  { value: "ISSUE_RO", label: "Issue RO" },
  { value: "LOADING", label: "Loading milestones" },
  { value: "REVIEW", label: "Review" },
];

function djAction(b: BookingDetail): DjAction {
  if (b.roHoldReason) {
    return { key: "RO_HOLD", label: "RO amendment hold", color: "red" };
  }
  if (b.clearanceCurrentPhase === "GL_DJ_LOADING") {
    return { key: "LOADING", label: "Loading milestones", color: "teal" };
  }
  if (b.tradeDirection === "IMPORT") {
    return { key: "COLLECT_DO", label: "Collect DO", color: "yellow" };
  }
  if (b.tradeDirection === "EXPORT") {
    return { key: "ISSUE_RO", label: "Issue RO", color: "blue" };
  }
  return { key: "REVIEW", label: "Review", color: "gray" };
}

// ── Row models ───────────────────────────────────────────────────────────────

interface ShipmentRow {
  id: string;
  reference: string;
  contractReference: string;
  customerLabel: string;
  originLabel: string;
  destinationLabel: string;
  tradeDirection: string;
  freightType: string;
  status: string;
  phase: string | null;
  roHoldReason: string | null;
  scheduledDate: string | null;
  weightTons: number;
  isHazardous: boolean;
  action: DjAction;
}

function toShipmentRow(b: BookingDetail): ShipmentRow {
  return {
    id: b.id,
    reference: b.reference,
    contractReference: b.contractReference ?? "—",
    customerLabel: b.company?.name ?? b.governmentInstitution ?? "—",
    originLabel: yardLabel(b.originYard),
    destinationLabel: yardLabel(b.destinationYard),
    tradeDirection: b.tradeDirection ?? "—",
    freightType: b.freightType ?? "—",
    status: b.status,
    phase: b.clearanceCurrentPhase ?? null,
    roHoldReason: b.roHoldReason ?? null,
    scheduledDate: b.scheduledDate ?? null,
    weightTons: b.cargoTotalWeightVgm ?? 0,
    isHazardous: Boolean(b.isHazardous),
    action: djAction(b),
  };
}

interface ContractRow {
  id: string;
  reference: string;
  customerLabel: string;
  originLabel: string;
  destinationLabel: string;
  tradeDirection: string;
  freightType: string;
  serviceTypeName: string;
  customs: boolean;
  status: string;
  clearanceStatus: string;
  phase: string | null;
  cycleNumber: number;
  validFrom: string | null;
  validUntil: string | null;
  validityDays: number | null;
  estimatedShipmentDate: string | null;
}

function toContractRow(c: Freight.IContract): ContractRow {
  const routes = [...(c.routes ?? [])].sort((a, b) => a.sortOrder - b.sortOrder);
  const first = routes[0];
  const last = routes[routes.length - 1] ?? first;
  return {
    id: c.id,
    reference: c.reference,
    customerLabel: c.isGovernment
      ? (c.governmentInstitution ?? "Government")
      : (c.company?.name ?? "—"),
    originLabel: yardLabel(first?.originYard),
    destinationLabel: yardLabel(last?.destinationYard),
    tradeDirection: c.tradeDirection ?? "—",
    freightType: c.freightType ?? "—",
    serviceTypeName: c.serviceType?.serviceName ?? "—",
    customs: c.serviceType?.includesCustoms ?? Boolean(c.customsClearingEnabled),
    status: c.status,
    clearanceStatus: c.clearanceStatus,
    phase: (c.clearancePhase as string | null) ?? null,
    cycleNumber: c.clearanceCycleNumber ?? 1,
    validFrom: c.contractValidFrom ?? null,
    validUntil: c.contractValidUntil ?? null,
    validityDays: c.contractValidityDays ?? null,
    estimatedShipmentDate: c.estimatedShipmentDate ?? null,
  };
}

// ── Shared cell pieces ───────────────────────────────────────────────────────

function DirectionIcon({ direction }: { direction: string }) {
  const isImport = direction === "IMPORT";
  const Icon = isImport ? Truck : ShipWheel;
  const label = directionLabel(direction);
  return (
    <Tooltip label={label} withArrow>
      <ThemeIcon
        variant="light"
        color={isImport ? "edr-green" : "gray"}
        radius="md"
        size={26}
        aria-label={label}
      >
        <Icon size={14} strokeWidth={1.9} />
      </ThemeIcon>
    </Tooltip>
  );
}

function RouteCell({
  origin,
  destination,
  direction,
  freightType,
}: {
  origin: string;
  destination: string;
  direction: string;
  freightType: string;
}) {
  return (
    <Stack gap={4} py={2}>
      <Group gap={6} wrap="nowrap">
        <Text size="sm" fw={500} truncate maw={120}>
          {origin}
        </Text>
        <ArrowRight size={14} className="shrink-0 text-muted-foreground" />
        <Text size="sm" fw={500} truncate maw={120}>
          {destination}
        </Text>
      </Group>
      <Group gap={8} align="center">
        <DirectionIcon direction={direction} />
        <Badge size="xs" variant="default" radius="sm">
          {freightType}
        </Badge>
      </Group>
    </Stack>
  );
}

// ── Page ─────────────────────────────────────────────────────────────────────

/**
 * GL Djibouti clearance queues:
 * - Contracts: ONE_TIME customs contracts in phased clearance (legacy flow).
 * - Shipments: GENERAL-contract bookings in per-booking clearance awaiting a DJ
 *   action (DO collection after ET finalizes pre-clearance, RO for exports,
 *   loading milestones). Managed like the one-time flow, but per booking.
 */
export default function GlDjiboutiClearanceListPage() {
  const navigate = useNavigate();
  const [tab, setTab] = useState<QueueTab>("shipments");
  const [query, setQuery] = useState("");
  const [direction, setDirection] = useState<string | null>(null);
  const [freight, setFreight] = useState<string | null>(null);
  const [status, setStatus] = useState<string | null>(null);
  const [action, setAction] = useState<string | null>(null);
  const { pagination, setPagination } = usePagination({ pageSize: 10 });

  const {
    data: contractQueue,
    isLoading: contractsLoading,
    isError: contractsError,
    isFetching: contractsFetching,
    refetch: refetchContracts,
  } = useDjClearanceQueue();
  const {
    data: bookingQueue,
    isLoading: bookingsLoading,
    isError: bookingsError,
    isFetching: bookingsFetching,
    refetch: refetchBookings,
  } = useBookingDjClearanceQueue();

  const resetPage = useCallback(
    () => setPagination({ pageIndex: 0, pageSize: pagination.pageSize }),
    [setPagination, pagination.pageSize],
  );

  const allShipmentRows = useMemo(
    () => (bookingQueue ?? []).map(toShipmentRow),
    [bookingQueue],
  );
  const allContractRows = useMemo(
    () => (contractQueue?.items ?? []).map(toContractRow),
    [contractQueue?.items],
  );

  // KPI metrics span both queues, regardless of active tab or filters.
  const metrics = useMemo(
    () => ({
      shipments: allShipmentRows.length,
      contracts: allContractRows.length,
      collectDo: allShipmentRows.filter((r) => r.action.key === "COLLECT_DO")
        .length,
      issueRo: allShipmentRows.filter((r) => r.action.key === "ISSUE_RO").length,
      roHolds: allShipmentRows.filter((r) => r.action.key === "RO_HOLD").length,
    }),
    [allShipmentRows, allContractRows],
  );

  const statusOptions = useMemo(() => {
    const source =
      tab === "shipments"
        ? allShipmentRows.map((r) => r.status)
        : allContractRows.map((r) => r.status);
    return [...new Set(source)].sort().map((s) => ({
      value: s,
      label: prettyStatus(s),
    }));
  }, [tab, allShipmentRows, allContractRows]);

  const matchesShared = useCallback(
    (
      r: {
        reference: string;
        customerLabel: string;
        originLabel: string;
        destinationLabel: string;
        tradeDirection: string;
        freightType: string;
        status: string;
      },
      extraSearchFields: string[] = [],
    ) => {
      if (direction && r.tradeDirection !== direction) return false;
      if (freight && r.freightType !== freight) return false;
      if (status && r.status !== status) return false;
      const q = query.trim().toLowerCase();
      if (!q) return true;
      return [
        r.reference,
        r.customerLabel,
        r.originLabel,
        r.destinationLabel,
        prettyStatus(r.status),
        ...extraSearchFields,
      ].some((v) => v.toLowerCase().includes(q));
    },
    [direction, freight, status, query],
  );

  const shipmentRows = useMemo(
    () =>
      allShipmentRows.filter(
        (r) =>
          (!action || r.action.key === action) &&
          // Shipments also match the parent contract reference in search.
          matchesShared(r, [r.contractReference]),
      ),
    [allShipmentRows, action, matchesShared],
  );

  const contractRows = useMemo(
    () => allContractRows.filter((r) => matchesShared(r)),
    [allContractRows, matchesShared],
  );

  const rows = tab === "shipments" ? shipmentRows : contractRows;
  const isLoading = tab === "contracts" ? contractsLoading : bookingsLoading;
  const isError = tab === "contracts" ? contractsError : bookingsError;
  const isFetching = contractsFetching || bookingsFetching;
  const total = rows.length;
  const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize));
  const showEmpty = !isLoading && !isError && total === 0;

  const pagedShipmentRows = useMemo(() => {
    const start = pagination.pageIndex * pagination.pageSize;
    return shipmentRows.slice(start, start + pagination.pageSize);
  }, [shipmentRows, pagination.pageIndex, pagination.pageSize]);

  const pagedContractRows = useMemo(() => {
    const start = pagination.pageIndex * pagination.pageSize;
    return contractRows.slice(start, start + pagination.pageSize);
  }, [contractRows, pagination.pageIndex, pagination.pageSize]);

  const hasFilters = Boolean(query || direction || freight || status || action);

  const clearFilters = useCallback(() => {
    setQuery("");
    setDirection(null);
    setFreight(null);
    setStatus(null);
    setAction(null);
    resetPage();
  }, [resetPage]);

  const handleRefresh = useCallback(() => {
    void refetchContracts();
    void refetchBookings();
  }, [refetchContracts, refetchBookings]);

  const openDetail = useCallback(
    (id: string) => navigate(`/dashboard/gl-djibouti/clearance/${id}`),
    [navigate],
  );

  const shipmentColumns: ColumnDef<ShipmentRow>[] = useMemo(
    () => [
      {
        id: "booking",
        header: () => <span className={bookingTable.headerCell}>Booking</span>,
        cell: ({ row }) => {
          const r = row.original;
          return (
            <div className="flex items-center gap-3 py-1.5">
              <div className={bookingTable.rowIcon}>
                <PackageCheck className="size-4" strokeWidth={1.75} />
              </div>
              <div className="min-w-0">
                <p className="truncate font-medium text-foreground">
                  {r.reference}
                </p>
                <p className="mt-0.5 flex items-center gap-1 truncate text-xs text-muted-foreground">
                  <User className="size-3 shrink-0 opacity-70" />
                  {r.customerLabel}
                </p>
              </div>
            </div>
          );
        },
      },
      {
        id: "contract",
        header: () => <span className={bookingTable.headerCell}>Contract</span>,
        cell: ({ row }) => (
          <Group gap={6} wrap="nowrap">
            <FileText size={13} className="shrink-0 text-muted-foreground" />
            <Text size="sm" truncate maw={140}>
              {row.original.contractReference}
            </Text>
          </Group>
        ),
      },
      {
        id: "route",
        header: () => <span className={bookingTable.headerCell}>Route</span>,
        cell: ({ row }) => {
          const r = row.original;
          return (
            <RouteCell
              origin={r.originLabel}
              destination={r.destinationLabel}
              direction={r.tradeDirection}
              freightType={r.freightType}
            />
          );
        },
      },
      {
        id: "cargo",
        header: () => <span className={bookingTable.headerCell}>Cargo</span>,
        cell: ({ row }) => {
          const r = row.original;
          return (
            <Stack gap={4} py={2}>
              <Group gap={6} wrap="nowrap">
                <Weight size={13} className="shrink-0 text-muted-foreground" />
                <Text size="sm">{r.weightTons} t</Text>
              </Group>
              {r.isHazardous ? (
                <Badge
                  size="xs"
                  variant="light"
                  color="red"
                  radius="sm"
                  leftSection={<AlertTriangle size={10} />}
                >
                  Hazardous
                </Badge>
              ) : null}
            </Stack>
          );
        },
      },
      {
        id: "action",
        header: () => <span className={bookingTable.headerCell}>DJ action</span>,
        cell: ({ row }) => {
          const r = row.original;
          const badge = (
            <Badge size="sm" variant="light" color={r.action.color} radius="sm">
              {r.action.label}
            </Badge>
          );
          return (
            <Stack gap={4} py={2}>
              {r.roHoldReason ? (
                <Tooltip label={r.roHoldReason} withArrow multiline maw={280}>
                  {badge}
                </Tooltip>
              ) : (
                badge
              )}
              <Text size="xs" c="dimmed">
                {phaseLabel(r.phase)}
              </Text>
            </Stack>
          );
        },
      },
      {
        id: "status",
        header: () => <span className={bookingTable.headerCell}>Status</span>,
        cell: ({ row }) => (
          <Badge
            size="sm"
            variant="light"
            color={statusColor(row.original.status)}
            radius="sm"
          >
            {prettyStatus(row.original.status)}
          </Badge>
        ),
      },
      {
        id: "scheduled",
        header: () => <span className={bookingTable.headerCell}>Scheduled</span>,
        cell: ({ row }) => (
          <Group gap={6} wrap="nowrap">
            <CalendarClock size={13} className="shrink-0 text-muted-foreground" />
            <Text size="sm" c="dimmed">
              {formatDate(row.original.scheduledDate)}
            </Text>
          </Group>
        ),
      },
      {
        id: "chevron",
        size: 40,
        header: "",
        cell: () => (
          <Group justify="flex-end" pr="xs">
            <ChevronRight size={16} className="text-muted-foreground" />
          </Group>
        ),
      },
    ],
    [],
  );

  const contractColumns: ColumnDef<ContractRow>[] = useMemo(
    () => [
      {
        id: "contract",
        header: () => <span className={bookingTable.headerCell}>Contract</span>,
        cell: ({ row }) => {
          const r = row.original;
          return (
            <div className="flex items-center gap-3 py-1.5">
              <div className={bookingTable.rowIcon}>
                <Ship className="size-4" strokeWidth={1.75} />
              </div>
              <div className="min-w-0">
                <p className="truncate font-medium text-foreground">
                  {r.reference}
                </p>
                <p className="mt-0.5 flex items-center gap-1 truncate text-xs text-muted-foreground">
                  <User className="size-3 shrink-0 opacity-70" />
                  {r.customerLabel}
                </p>
              </div>
            </div>
          );
        },
      },
      {
        id: "route",
        header: () => <span className={bookingTable.headerCell}>Route</span>,
        cell: ({ row }) => {
          const r = row.original;
          return (
            <RouteCell
              origin={r.originLabel}
              destination={r.destinationLabel}
              direction={r.tradeDirection}
              freightType={r.freightType}
            />
          );
        },
      },
      {
        id: "service",
        header: () => <span className={bookingTable.headerCell}>Service</span>,
        cell: ({ row }) => {
          const r = row.original;
          return (
            <Stack gap={4} py={2} style={{ minWidth: 0 }}>
              <Text size="sm" fw={500} truncate maw={160}>
                {r.serviceTypeName}
              </Text>
              {r.customs ? (
                <Badge
                  size="xs"
                  variant="light"
                  color="edr-green"
                  radius="sm"
                  leftSection={<ShieldCheck size={11} />}
                >
                  Customs
                </Badge>
              ) : (
                <Badge size="xs" variant="light" color="gray" radius="sm">
                  No customs
                </Badge>
              )}
            </Stack>
          );
        },
      },
      {
        id: "clearance",
        header: () => <span className={bookingTable.headerCell}>Clearance</span>,
        cell: ({ row }) => {
          const r = row.original;
          return (
            <Stack gap={4} py={2}>
              <Badge
                size="sm"
                variant="light"
                color={statusColor(r.clearanceStatus)}
                radius="sm"
              >
                {prettyStatus(r.clearanceStatus)}
              </Badge>
              <Text size="xs" c="dimmed">
                {phaseLabel(r.phase)}
                {r.cycleNumber > 1 ? ` · Cycle ${r.cycleNumber}` : ""}
              </Text>
            </Stack>
          );
        },
      },
      {
        id: "status",
        header: () => <span className={bookingTable.headerCell}>Status</span>,
        cell: ({ row }) => (
          <Badge
            size="sm"
            variant="light"
            color={statusColor(row.original.status)}
            radius="sm"
          >
            {prettyStatus(row.original.status)}
          </Badge>
        ),
      },
      {
        id: "validity",
        header: () => <span className={bookingTable.headerCell}>Validity</span>,
        cell: ({ row }) => {
          const r = row.original;
          return (
            <Stack gap={2} py={2}>
              <Group gap={6} wrap="nowrap">
                <CalendarClock
                  size={13}
                  className="shrink-0 text-muted-foreground"
                />
                <Text size="sm" c="dimmed">
                  {r.validUntil
                    ? `Until ${formatDate(r.validUntil)}`
                    : r.validityDays
                      ? `${r.validityDays} days`
                      : "—"}
                </Text>
              </Group>
              {r.estimatedShipmentDate ? (
                <Text size="xs" c="dimmed">
                  Est. shipment {formatDate(r.estimatedShipmentDate)}
                </Text>
              ) : null}
            </Stack>
          );
        },
      },
      {
        id: "chevron",
        size: 40,
        header: "",
        cell: () => (
          <Group justify="flex-end" pr="xs">
            <ChevronRight size={16} className="text-muted-foreground" />
          </Group>
        ),
      },
    ],
    [],
  );

  return (
    <PageContainer>
      <Stack gap="lg">
        <PageHeader
          title="GL Djibouti — Clearance"
          subtitle="Customs contracts and shipment bookings handed off to Djibouti GL."
          action={
            <ActionIcon
              variant="default"
              size="lg"
              radius="md"
              loading={isFetching}
              onClick={handleRefresh}
              aria-label="Refresh"
            >
              <RefreshCw size={16} />
            </ActionIcon>
          }
        />

        <KpiStrip
          loading={contractsLoading || bookingsLoading}
          items={[
            {
              label: "Shipments in queue",
              value: metrics.shipments,
              icon: PackageCheck,
              color: "blue",
            },
            {
              label: "Contracts in queue",
              value: metrics.contracts,
              icon: FileSignature,
              color: "edr-green",
            },
            {
              label: "Imports — collect DO",
              value: metrics.collectDo,
              icon: Truck,
              color: "yellow",
            },
            {
              label: "Exports — issue RO",
              value: metrics.issueRo,
              icon: ShipWheel,
              color: "blue",
            },
            {
              label: "RO amendment holds",
              value: metrics.roHolds,
              icon: AlertTriangle,
              color: "red",
            },
          ]}
        />

        <Card p={0} withBorder shadow="sm" radius="lg">
          <Stack gap={0}>
            <Box px="md" pt="md">
              <SegmentedControl
                size="sm"
                value={tab}
                onChange={(v) => {
                  setTab(v as QueueTab);
                  setStatus(null);
                  setAction(null);
                  resetPage();
                }}
                radius="md"
                data={[
                  {
                    value: "shipments",
                    label: (
                      <Group gap={6} wrap="nowrap">
                        <PackageCheck size={15} />
                        <Box visibleFrom="sm">Shipments</Box>
                        <Badge size="sm" radius="sm" variant="light" color="edr-green">
                          {allShipmentRows.length}
                        </Badge>
                      </Group>
                    ),
                  },
                  {
                    value: "contracts",
                    label: (
                      <Group gap={6} wrap="nowrap">
                        <FileSignature size={15} />
                        <Box visibleFrom="sm">Contracts</Box>
                        <Badge size="sm" radius="sm" variant="light" color="gray">
                          {allContractRows.length}
                        </Badge>
                      </Group>
                    ),
                  },
                ]}
              />
            </Box>

            <Box px="md" pt="md" pb="sm">
              <Group gap="sm" wrap="wrap">
                <TextInput
                  placeholder="Search reference, customer, route, or status…"
                  leftSection={<Search size={18} />}
                  value={query}
                  onChange={(e) => {
                    setQuery(e.currentTarget.value);
                    resetPage();
                  }}
                  rightSection={
                    query ? (
                      <ActionIcon
                        size="sm"
                        color="gray"
                        radius="md"
                        variant="transparent"
                        onClick={() => {
                          setQuery("");
                          resetPage();
                        }}
                      >
                        <X size={16} />
                      </ActionIcon>
                    ) : null
                  }
                  radius="lg"
                  style={{ flex: 1, minWidth: 220 }}
                />
                <Select
                  placeholder="Direction"
                  data={[
                    { value: "IMPORT", label: "Import" },
                    { value: "EXPORT", label: "Export" },
                  ]}
                  value={direction}
                  onChange={(v) => {
                    setDirection(v);
                    resetPage();
                  }}
                  clearable
                  radius="lg"
                  w={130}
                />
                <Select
                  placeholder="Freight"
                  data={[
                    { value: "CONTAINER", label: "Container" },
                    { value: "BULK", label: "Bulk" },
                  ]}
                  value={freight}
                  onChange={(v) => {
                    setFreight(v);
                    resetPage();
                  }}
                  clearable
                  radius="lg"
                  w={130}
                />
                <Select
                  placeholder="Status"
                  data={statusOptions}
                  value={status}
                  onChange={(v) => {
                    setStatus(v);
                    resetPage();
                  }}
                  clearable
                  radius="lg"
                  w={190}
                />
                {tab === "shipments" ? (
                  <Select
                    placeholder="DJ action"
                    data={DJ_ACTION_OPTIONS}
                    value={action}
                    onChange={(v) => {
                      setAction(v);
                      resetPage();
                    }}
                    clearable
                    radius="lg"
                    w={180}
                  />
                ) : null}
                {hasFilters ? (
                  <Button
                    variant="subtle"
                    color="gray"
                    size="compact-sm"
                    radius="md"
                    leftSection={<X size={14} />}
                    onClick={clearFilters}
                  >
                    Clear
                  </Button>
                ) : null}
                <Text size="sm" c="dimmed" ml="auto">
                  {total} record{total !== 1 ? "s" : ""}
                </Text>
              </Group>
            </Box>

            {showEmpty ? (
              <Stack align="center" gap={8} py={48}>
                <ThemeIcon variant="light" color="gray" radius="xl" size={48}>
                  <Inbox size={22} />
                </ThemeIcon>
                <Text c="dimmed">
                  {hasFilters
                    ? "No records match these filters."
                    : tab === "contracts"
                      ? "No Djibouti customs contracts yet."
                      : "No shipment bookings awaiting a Djibouti action."}
                </Text>
                {hasFilters ? (
                  <Button
                    variant="light"
                    color="gray"
                    size="compact-sm"
                    radius="md"
                    onClick={clearFilters}
                  >
                    Clear filters
                  </Button>
                ) : null}
              </Stack>
            ) : (
              <Box style={{ overflowX: "auto" }} px="xs" pb="xs">
                {tab === "shipments" ? (
                  <DataTable<ShipmentRow, unknown>
                    columns={shipmentColumns}
                    data={pagedShipmentRows}
                    status={isLoading ? "loading" : isError ? "error" : "success"}
                    onRowClick={(row) => openDetail(row.id)}
                    pagination={{
                      pageIndex: pagination.pageIndex,
                      pageSize: pagination.pageSize,
                      pageCount,
                      totalCount: total,
                    }}
                    tableOptions={{
                      state: { pagination },
                      onPaginationChange: setPagination,
                      manualPagination: true,
                      pageCount,
                    }}
                    containerClassName="border-0 shadow-none bg-transparent"
                    footer={DataTableFooter}
                  />
                ) : (
                  <DataTable<ContractRow, unknown>
                    columns={contractColumns}
                    data={pagedContractRows}
                    status={isLoading ? "loading" : isError ? "error" : "success"}
                    onRowClick={(row) => openDetail(row.id)}
                    pagination={{
                      pageIndex: pagination.pageIndex,
                      pageSize: pagination.pageSize,
                      pageCount,
                      totalCount: total,
                    }}
                    tableOptions={{
                      state: { pagination },
                      onPaginationChange: setPagination,
                      manualPagination: true,
                      pageCount,
                    }}
                    containerClassName="border-0 shadow-none bg-transparent"
                    footer={DataTableFooter}
                  />
                )}
              </Box>
            )}
          </Stack>
        </Card>
      </Stack>
    </PageContainer>
  );
}
