"use client";

import { useReducer } from "react";
import Link from "next/link";
import { Truck, Search, Package, ExternalLink, Sprout, X } from "lucide-react";
import { updateShippingStatus } from "@/actions/shipping";
import { getFedExRates, type FedExRate, type FedExServiceType } from "@/actions/shipping/fedex-rates";
import { createFedExShipment } from "@/actions/shipping/fedex-labels";
import AdminButton from "./design-system/AdminButton";
import AdminSearchInput from "./design-system/AdminSearchInput";
import AdminFilterTabs from "./design-system/AdminFilterTabs";
import AdminBadge from "./design-system/AdminBadge";
import AdminEmptyState from "./design-system/AdminEmptyState";
import AdminCard from "./design-system/AdminCard";
import GlassModal from "./GlassModal";

type OrderItem = {
  id: string;
  product_id: string;
  quantity: number;
  price: number;
  fulfillment: string;
  products: { name: string; is_perishable: boolean } | null;
};

type ShippingOrder = {
  id: string;
  customer_name: string;
  customer_email: string | null;
  customer_phone: string | null;
  status: string;
  subtotal: number;
  shipping_status: string;
  tracking_number: string | null;
  created_at: string;
  brand_id: string | null;
  order_items: OrderItem[];
};

type ShippingFulfillmentPanelProps = {
  initialOrders: ShippingOrder[];
  canManageOrders: boolean;
};

type ShippingStatus = "pending" | "label_created" | "shipped" | "delivered" | "returned";

const SHIPPING_STATUSES: Array<{ value: ShippingStatus; label: string }> = [
  { value: "pending", label: "Pending" },
  { value: "label_created", label: "Label Created" },
  { value: "shipped", label: "Shipped" },
  { value: "delivered", label: "Delivered" },
  { value: "returned", label: "Returned" },
];

const SERVICE_LABELS: Record<FedExServiceType, string> = {
  FEDEX_OVERNIGHT: "FedEx Overnight",
  FEDEX_2_DAY_AIR: "FedEx 2-Day Air",
  FEDEX_EXPRESS_SAVER: "FedEx Express Saver",
  FEDEX_GROUND: "FedEx Ground",
};

const STATUS_TONE: Record<ShippingStatus | string, "warning" | "info" | "primary" | "success" | "danger" | "neutral"> = {
  pending: "warning",
  label_created: "info",
  shipped: "primary",
  delivered: "success",
  returned: "danger",
};

function shortId(id: string) {
  return id.slice(0, 8).toUpperCase();
}

const currencyFormatter = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });

function formatCurrency(amount: number) {
  return currencyFormatter.format(amount);
}

function statusLabel(status: string) {
  return SHIPPING_STATUSES.find((s) => s.value === status)?.label ?? status;
}

// ── Rate Modal ────────────────────────────────────────────────────────────────

type RateState = {
  rates: FedExRate[] | null;
  loading: boolean;
  error: string | null;
  creating: FedExServiceType | null;
  createError: string | null;
  result: { labelUrl: string; trackingNumber: string } | null;
};

type RateAction =
  | { type: "START_LOAD" }
  | { type: "LOAD_SUCCESS"; rates: FedExRate[] }
  | { type: "LOAD_FAIL"; error: string }
  | { type: "START_CREATE"; serviceType: FedExServiceType }
  | { type: "CREATE_SUCCESS"; labelUrl: string; trackingNumber: string }
  | { type: "CREATE_FAIL"; error: string };

const initialRateState: RateState = {
  rates: null,
  loading: false,
  error: null,
  creating: null,
  createError: null,
  result: null,
};

function rateReducer(state: RateState, action: RateAction): RateState {
  switch (action.type) {
    case "START_LOAD":
      return { ...state, loading: true, error: null };
    case "LOAD_SUCCESS":
      return { ...state, loading: false, rates: action.rates };
    case "LOAD_FAIL":
      return { ...state, loading: false, error: action.error };
    case "START_CREATE":
      return { ...state, creating: action.serviceType, createError: null };
    case "CREATE_SUCCESS":
      return {
        ...state,
        creating: null,
        result: { labelUrl: action.labelUrl, trackingNumber: action.trackingNumber },
      };
    case "CREATE_FAIL":
      return { ...state, creating: null, createError: action.error };
  }
}

function RateModal({
  order,
  onClose,
}: {
  order: ShippingOrder;
  onClose: () => void;
}) {
  const [state, dispatch] = useReducer(rateReducer, initialRateState);
  const { rates, loading, error, creating, createError, result } = state;

  async function loadRates() {
    dispatch({ type: "START_LOAD" });
    const res = await getFedExRates(order.id);
    if (res.success) {
      dispatch({ type: "LOAD_SUCCESS", rates: res.rates });
    } else {
      dispatch({ type: "LOAD_FAIL", error: res.error ?? "Failed to load rates" });
    }
  }

  async function handleSelectRate(rate: FedExRate) {
    dispatch({ type: "START_CREATE", serviceType: rate.serviceType });
    const res = await createFedExShipment(
      order.id,
      rate.serviceType,
      rate.totalCharge,
      rate.deliveryDate
    );
    if (res.success) {
      dispatch({
        type: "CREATE_SUCCESS",
        labelUrl: res.labelUrl,
        trackingNumber: res.trackingNumber,
      });
    } else {
      dispatch({ type: "CREATE_FAIL", error: res.error ?? "Failed to create shipment" });
    }
  }

  // Auto-load on mount
  if (rates === null && !loading && !error) {
    loadRates();
  }

  return (
    <GlassModal
      title="Shipping Rates"
      subtitle={`${order.customer_name} · ${shortId(order.id)}`}
      onClose={onClose}
      maxWidth="max-w-lg"
    >
      <div className="space-y-4">
        <RateModalBody
          rates={rates}
          loading={loading}
          error={error}
          creating={creating}
          createError={createError}
          result={result}
          onRetry={loadRates}
          onSelectRate={handleSelectRate}
          onClose={onClose}
        />
      </div>
    </GlassModal>
  );
}

function RateModalBody({
  rates,
  loading,
  error,
  creating,
  createError,
  result,
  onRetry,
  onSelectRate,
  onClose,
}: {
  rates: FedExRate[] | null;
  loading: boolean;
  error: string | null;
  creating: FedExServiceType | null;
  createError: string | null;
  result: { labelUrl: string; trackingNumber: string } | null;
  onRetry: () => void;
  onSelectRate: (rate: FedExRate) => void;
  onClose: () => void;
}) {
  return (
    <>
      {/* Perishable warning */}
      {rates !== null && rates[0]?.isPerishableOnly && (
        <div
          className="rounded-xl border px-4 py-3 text-sm"
          style={{
            backgroundColor: "var(--admin-warning-soft)",
            borderColor: "var(--admin-warning)",
            color: "var(--admin-warning)",
          }}
        >
          <strong>Perishable shipment.</strong> Only Overnight and 2-Day Air are available
          for fresh produce (sweet corn, onions, etc.). Ground and Express Saver are not
          offered for temperature-sensitive items.
        </div>
      )}

      {loading && (
        <div className="flex items-center justify-center py-12 gap-3">
          <div
            className="h-5 w-5 rounded-full border-2 border-t-transparent animate-spin"
            style={{ borderColor: "var(--admin-accent)", borderTopColor: "transparent" }}
          />
          <span style={{ color: "var(--admin-text-muted)" }}>Fetching FedEx rates...</span>
        </div>
      )}

      {error && (
        <div
          className="rounded-xl border px-4 py-3 text-sm"
          style={{
            backgroundColor: "var(--admin-danger-soft)",
            borderColor: "var(--admin-danger)",
            color: "var(--admin-danger)",
          }}
        >
          {error}
          <button type="button"
            onClick={onRetry}
            className="ml-2 underline hover:no-underline font-semibold"
          >
            Retry
          </button>
        </div>
      )}

      {rates !== null && rates.length === 0 && !loading && (
        <AdminEmptyState
          title="No rates available"
          description="No FedEx rates returned for this address. Please verify the shipping address is complete."
        />
      )}

      {rates !== null && rates.length > 0 && (
        <div className="space-y-2">
          {rates.map((rate) => (
            <button type="button"
              key={rate.serviceType}
              onClick={() => onSelectRate(rate)}
              disabled={creating !== null}
              className="w-full flex items-center justify-between rounded-xl border px-4 py-3 text-left transition-all duration-150 disabled:opacity-50 disabled:cursor-not-allowed"
              style={{
                borderColor: "var(--admin-border)",
                backgroundColor: "var(--admin-card-bg)",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.borderColor = "var(--admin-accent)";
                e.currentTarget.style.backgroundColor = "var(--admin-accent-soft)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.borderColor = "var(--admin-border)";
                e.currentTarget.style.backgroundColor = "var(--admin-card-bg)";
              }}
            >
              <div>
                <div
                  className="font-semibold"
                  style={{ color: "var(--admin-text-primary)" }}
                >
                  {SERVICE_LABELS[rate.serviceType] ?? rate.serviceType}
                </div>
                <div
                  className="text-xs mt-0.5"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  {rate.deliveryDateLabel
                    ? `Arrives ${rate.deliveryDateLabel}`
                    : rate.deliveryDayOfWeek}
                </div>
                {rate.isPerishableOnly && (
                  <span className="mt-1.5 inline-block">
                    <AdminBadge tone="warning">Required for perishable</AdminBadge>
                  </span>
                )}
              </div>
              <div className="text-right">
                <div
                  className="ha-num font-bold"
                  style={{ color: "var(--admin-text-primary)" }}
                >
                  {formatCurrency(rate.totalCharge / 100)}
                </div>
                {creating === rate.serviceType && (
                  <div
                    className="h-4 w-4 rounded-full border-2 border-t-transparent animate-spin mt-1 mx-auto"
                    style={{
                      borderColor: "var(--admin-accent)",
                      borderTopColor: "transparent",
                    }}
                  />
                )}
              </div>
            </button>
          ))}
        </div>
      )}

      {createError && (
        <div
          className="rounded-xl border px-4 py-3 text-sm"
          style={{
            backgroundColor: "var(--admin-danger-soft)",
            borderColor: "var(--admin-danger)",
            color: "var(--admin-danger)",
          }}
        >
          {createError}
        </div>
      )}

      {result && <RateCreatedResult result={result} onClose={onClose} />}
    </>
  );
}

function RateCreatedResult({
  result,
  onClose,
}: {
  result: { labelUrl: string; trackingNumber: string };
  onClose: () => void;
}) {
  return (
    <div
      className="rounded-xl border px-4 py-4 space-y-3"
      style={{
        backgroundColor: "var(--admin-primary-soft)",
        borderColor: "var(--admin-primary)",
      }}
    >
      <div
        className="flex items-center gap-2 font-semibold"
        style={{ color: "var(--admin-primary)" }}
      >
        <span className="text-lg">✓</span> Label Created
      </div>
      <div
        className="text-sm"
        style={{ color: "var(--admin-primary)" }}
      >
        <div>
          Tracking:{" "}
          <span
            className="font-mono-ui font-medium"
            style={{ color: "var(--admin-text-primary)" }}
          >
            {result.trackingNumber}
          </span>
        </div>
      </div>
      <div className="flex flex-wrap gap-2">
        {result.labelUrl && (
          <a
            href={result.labelUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-1.5 rounded-xl px-4 py-2 text-sm font-semibold text-white transition-colors"
            style={{ backgroundColor: "var(--admin-primary)" }}
          >
            <ExternalLink className="h-4 w-4" strokeWidth={2} />
            Download Label
          </a>
        )}
        <AdminButton variant="secondary" size="md" onClick={onClose}>
          Done
        </AdminButton>
      </div>
    </div>
  );
}

// ── Order Card ────────────────────────────────────────────────────────────────

function OrderCard({
  order,
  canManageOrders,
  updating,
  trackingInputs,
  onTrackingInputChange,
  onStatusChange,
  onOpenRateModal,
}: {
  order: ShippingOrder;
  canManageOrders: boolean;
  updating: string | null;
  trackingInputs: Record<string, string>;
  onTrackingInputChange: (orderId: string, value: string) => void;
  onStatusChange: (orderId: string, status: string) => void;
  onOpenRateModal: (order: ShippingOrder) => void;
}) {
  const tone = STATUS_TONE[order.shipping_status] ?? "neutral";
  const shipItems = order.order_items.filter((i) => i.fulfillment === "ship");
  const hasShipItems = shipItems.length > 0;
  const hasPerishableItems = order.order_items.some(
    (i) => i.fulfillment === "ship" && i.products?.is_perishable
  );
  const isPending =
    order.shipping_status === "pending" || order.shipping_status === "label_created";
  const isBusy = updating === order.id;
  // Collapse the (hasShipItems AND isPending) pair into a single
  // derived flag so OrderCardActions has fewer boolean props.
  const showActions = hasShipItems && isPending;

  return (
    <AdminCard noPadding className="overflow-hidden">
      <div className="p-4 sm:p-5 space-y-4">
        <OrderCardHeader
          order={order}
          tone={tone}
          hasPerishableItems={hasPerishableItems}
          isPending={isPending}
        />
        {order.tracking_number && (
          <OrderCardTracking
            order={order}
            canManageOrders={canManageOrders}
            isBusy={isBusy}
            onStatusChange={onStatusChange}
          />
        )}
        {shipItems.length > 0 && <OrderCardItems order={order} shipItems={shipItems} />}
        <OrderCardActions
          order={order}
          canManageOrders={canManageOrders}
          showActions={showActions}
          isBusy={isBusy}
          trackingInputs={trackingInputs}
          onTrackingInputChange={onTrackingInputChange}
          onStatusChange={onStatusChange}
          onOpenRateModal={onOpenRateModal}
        />
      </div>
    </AdminCard>
  );
}

function OrderCardHeader({
  order,
  tone,
  hasPerishableItems,
  isPending,
}: {
  order: ShippingOrder;
  tone: "warning" | "info" | "primary" | "success" | "danger" | "neutral";
  hasPerishableItems: boolean;
  isPending: boolean;
}) {
  return (
    <>
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <p
            className="text-base sm:text-lg font-bold truncate"
            style={{ color: "var(--admin-text-primary)" }}
          >
            {order.customer_name}
          </p>
          {order.customer_phone && (
            <p
              className="mt-0.5 text-sm"
              style={{ color: "var(--admin-text-muted)" }}
            >
              {order.customer_phone}
            </p>
          )}
          <p
            className="mt-0.5 font-mono-ui text-[10px] uppercase tracking-widest"
            style={{ color: "var(--admin-text-muted)" }}
          >
            {shortId(order.id)}
          </p>
        </div>
        <AdminBadge tone={tone} dot className="shrink-0">
          {statusLabel(order.shipping_status)}
        </AdminBadge>
      </div>

      {hasPerishableItems && isPending && (
        <div
          className="flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-semibold"
          style={{
            backgroundColor: "var(--admin-warning-soft)",
            borderColor: "var(--admin-warning)",
            color: "var(--admin-warning)",
          }}
        >
          <Sprout className="h-3.5 w-3.5" strokeWidth={2} />
          Perishable — Overnight or 2-Day Air only
        </div>
      )}
    </>
  );
}

function OrderCardTracking({
  order,
  canManageOrders,
  isBusy,
  onStatusChange,
}: {
  order: ShippingOrder;
  canManageOrders: boolean;
  isBusy: boolean;
  onStatusChange: (orderId: string, status: string) => void;
}) {
  return (
    <div
      className="flex flex-wrap items-center justify-between gap-2 rounded-xl border px-3 py-2 text-sm"
      style={{
        borderColor: "var(--admin-border-light)",
        backgroundColor: "var(--admin-bg-subtle)",
      }}
    >
      <div>
        <span style={{ color: "var(--admin-text-muted)" }}>Tracking: </span>
        <span
          className="font-mono-ui font-medium"
          style={{ color: "var(--admin-text-primary)" }}
        >
          {order.tracking_number}
        </span>
      </div>
      {order.shipping_status === "label_created" && canManageOrders && (
        <AdminButton
          variant="primary"
          size="sm"
          onClick={() => onStatusChange(order.id, "shipped")}
          disabled={isBusy}
          isLoading={isBusy}
        >
          Mark Shipped
        </AdminButton>
      )}
    </div>
  );
}

function OrderCardItems({
  order,
  shipItems,
}: {
  order: ShippingOrder;
  shipItems: OrderItem[];
}) {
  return (
    <div
      className="rounded-xl p-3"
      style={{ backgroundColor: "var(--admin-bg-subtle)" }}
    >
      <ul className="space-y-1">
        {shipItems.map((item) => (
          <li
            key={item.id}
            className="flex items-center justify-between text-sm"
          >
            <span style={{ color: "var(--admin-text-secondary)" }}>
              {item.quantity > 1 && (
                <span
                  className="font-semibold"
                  style={{ color: "var(--admin-text-primary)" }}
                >
                  {item.quantity}×{" "}
                </span>
              )}
              {item.products?.name ?? "Unknown Product"}
              {item.products?.is_perishable && (
                <span
                  className="ml-1.5 inline-flex items-center gap-1 text-xs"
                  style={{ color: "var(--admin-warning)" }}
                >
                  <Sprout className="h-3 w-3" strokeWidth={2} />
                  perishable
                </span>
              )}
            </span>
            <span
              className="ha-num"
              style={{ color: "var(--admin-text-muted)" }}
            >
              {formatCurrency(Number(item.price) * item.quantity)}
            </span>
          </li>
        ))}
      </ul>
      <div
        className="mt-2 pt-2 flex justify-between"
        style={{ borderTop: "1px solid var(--admin-border-light)" }}
      >
        <span
          className="text-sm font-semibold"
          style={{ color: "var(--admin-text-secondary)" }}
        >
          Subtotal
        </span>
        <span
          className="ha-num text-sm font-bold"
          style={{ color: "var(--admin-text-primary)" }}
        >
          {formatCurrency(Number(order.subtotal))}
        </span>
      </div>
    </div>
  );
}

function OrderCardActions({
  order,
  canManageOrders,
  showActions,
  isBusy,
  trackingInputs,
  onTrackingInputChange,
  onStatusChange,
  onOpenRateModal,
}: {
  order: ShippingOrder;
  canManageOrders: boolean;
  showActions: boolean;
  isBusy: boolean;
  trackingInputs: Record<string, string>;
  onTrackingInputChange: (orderId: string, value: string) => void;
  onStatusChange: (orderId: string, status: string) => void;
  onOpenRateModal: (order: ShippingOrder) => void;
}) {
  if (!canManageOrders) {
    return (
      <div
        className="rounded-xl px-4 py-3 text-center text-sm"
        style={{
          backgroundColor: "var(--admin-bg-subtle)",
          color: "var(--admin-text-muted)",
        }}
      >
        No order management permission
      </div>
    );
  }

  if (!showActions) return null;

  return (
    <div className="flex flex-wrap gap-2">
      {order.shipping_status === "pending" && (
        <AdminButton
          variant="primary"
          size="sm"
          onClick={() => onOpenRateModal(order)}
          icon={<Truck className="h-4 w-4" strokeWidth={2} />}
          iconPosition="left"
        >
          Get FedEx Rates
        </AdminButton>
      )}

      {(order.shipping_status === "pending" ||
        order.shipping_status === "label_created") && (
        <input aria-label="Enter Tracking Manually"
          type="text"
          placeholder="Enter tracking manually"
          value={trackingInputs[order.id] ?? ""}
          onChange={(e) => onTrackingInputChange(order.id, e.target.value)}
          className="flex-1 min-w-[160px] rounded-xl border px-3 py-1.5 text-sm outline-none transition-colors"
          style={{
            borderColor: "var(--admin-border)",
            backgroundColor: "var(--admin-card-bg)",
            color: "var(--admin-text-primary)",
          }}
          onFocus={(e) => {
            e.currentTarget.style.borderColor = "var(--admin-accent)";
          }}
          onBlur={(e) => {
            e.currentTarget.style.borderColor = "var(--admin-border)";
          }}
        />
      )}

      {SHIPPING_STATUSES.reduce<typeof SHIPPING_STATUSES>((acc, s) => {
        if (s.value !== order.shipping_status && s.value !== "label_created") acc.push(s);
        return acc;
      }, []).map((s) => {
        const isDanger = s.value === "returned";
        return (
          <AdminButton
            key={s.value}
            variant={isDanger ? "danger" : "secondary"}
            size="sm"
            onClick={() => onStatusChange(order.id, s.value)}
            disabled={isBusy}
            isLoading={isBusy}
          >
            {`Mark ${s.label}`}
          </AdminButton>
        );
      })}
    </div>
  );
}

// ── Main Panel ────────────────────────────────────────────────────────────────

type State = {
  orders: ShippingOrder[];
  search: string;
  statusFilter: string;
  updating: string | null;
  trackingInputs: Record<string, string>;
  rateModalOrder: ShippingOrder | null;
};

type Action =
  | { type: "SET_ORDERS"; orders: ShippingOrder[] }
  | { type: "UPDATE_ORDER"; orderId: string; shippingStatus: string; trackingNumber: string | null }
  | { type: "SET_SEARCH"; value: string }
  | { type: "SET_STATUS_FILTER"; value: string }
  | { type: "START_UPDATING"; orderId: string }
  | { type: "STOP_UPDATING" }
  | { type: "SET_TRACKING"; orderId: string; value: string }
  | { type: "OPEN_RATE_MODAL"; order: ShippingOrder }
  | { type: "CLOSE_RATE_MODAL" }
  | { type: "CLEAR_FILTERS" };

const initialState: State = {
  orders: [],
  search: "",
  statusFilter: "",
  updating: null,
  trackingInputs: {},
  rateModalOrder: null,
};

function initState(initialOrders: ShippingOrder[]): State {
  return { ...initialState, orders: initialOrders };
}

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_ORDERS":
      return { ...state, orders: action.orders };
    case "UPDATE_ORDER":
      return {
        ...state,
        orders: state.orders.map((o) =>
          o.id === action.orderId
            ? {
                ...o,
                shipping_status: action.shippingStatus,
                tracking_number: action.trackingNumber ?? o.tracking_number,
              }
            : o
        ),
      };
    case "SET_SEARCH":
      return { ...state, search: action.value };
    case "SET_STATUS_FILTER":
      return { ...state, statusFilter: action.value };
    case "START_UPDATING":
      return { ...state, updating: action.orderId };
    case "STOP_UPDATING":
      return { ...state, updating: null };
    case "SET_TRACKING":
      return {
        ...state,
        trackingInputs: { ...state.trackingInputs, [action.orderId]: action.value },
      };
    case "OPEN_RATE_MODAL":
      return { ...state, rateModalOrder: action.order };
    case "CLOSE_RATE_MODAL":
      return { ...state, rateModalOrder: null };
    case "CLEAR_FILTERS":
      return { ...state, search: "", statusFilter: "" };
  }
}

export default function ShippingFulfillmentPanel({
  initialOrders,
  canManageOrders,
}: ShippingFulfillmentPanelProps) {
  const [state, dispatch] = useReducer(reducer, initialOrders, initState);
  const { orders, search, statusFilter, updating, trackingInputs, rateModalOrder } = state;

  const filtered = orders.filter((o) => {
    const matchesSearch =
      !search ||
      o.customer_name.toLowerCase().includes(search.toLowerCase()) ||
      (o.customer_phone ?? "").includes(search) ||
      o.id.includes(search.toUpperCase().slice(0, 8));

    const matchesStatus = !statusFilter || o.shipping_status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const counts: Record<string, number> = { all: orders.length };
  for (const s of SHIPPING_STATUSES) {
    counts[s.value] = orders.filter((o) => o.shipping_status === s.value).length;
  }

  const tabs = [
    { value: "", label: "All", count: counts.all },
    ...SHIPPING_STATUSES.map((s) => ({ value: s.value, label: s.label, count: counts[s.value] ?? 0 })),
  ];

  async function handleStatusChange(orderId: string, newStatus: string) {
    if (!canManageOrders) return;
    dispatch({ type: "START_UPDATING", orderId });

    const trackingNumber =
      newStatus === "shipped" ? trackingInputs[orderId] ?? null : null;

    const result = await updateShippingStatus(orderId, newStatus, trackingNumber ?? undefined);

    if (result.success) {
      dispatch({
        type: "UPDATE_ORDER",
        orderId,
        shippingStatus: newStatus,
        trackingNumber,
      });
    }

    dispatch({ type: "STOP_UPDATING" });
  }

  function handleTrackingInputChange(orderId: string, value: string) {
    dispatch({ type: "SET_TRACKING", orderId, value });
  }

  return (
    <div className="space-y-4">
      <ShippingFilterBar
        search={search}
        statusFilter={statusFilter}
        orderCount={orders.length}
        tabs={tabs}
        onSearchChange={(v) => dispatch({ type: "SET_SEARCH", value: v })}
        onStatusFilterChange={(v) => dispatch({ type: "SET_STATUS_FILTER", value: v })}
      />

      {filtered.length === 0 ? (
        <ShippingEmptyState
          hasFilter={Boolean(search || statusFilter)}
          onClear={() => dispatch({ type: "CLEAR_FILTERS" })}
        />
      ) : (
        <div className="space-y-3">
          {filtered.map((order) => (
            <OrderCard
              key={order.id}
              order={order}
              canManageOrders={canManageOrders}
              updating={updating}
              trackingInputs={trackingInputs}
              onTrackingInputChange={handleTrackingInputChange}
              onStatusChange={handleStatusChange}
              onOpenRateModal={(o) => dispatch({ type: "OPEN_RATE_MODAL", order: o })}
            />
          ))}
        </div>
      )}

      {rateModalOrder && (
        <RateModal order={rateModalOrder} onClose={() => dispatch({ type: "CLOSE_RATE_MODAL" })} />
      )}
    </div>
  );
}

function ShippingFilterBar({
  search,
  statusFilter,
  orderCount,
  tabs,
  onSearchChange,
  onStatusFilterChange,
}: {
  search: string;
  statusFilter: string;
  orderCount: number;
  tabs: { value: string; label: string; count: number }[];
  onSearchChange: (value: string) => void;
  onStatusFilterChange: (value: string) => void;
}) {
  return (
    <div
      className="rounded-2xl border p-4 shadow-[var(--admin-shadow-sm)]"
      style={{
        borderColor: "var(--admin-border)",
        backgroundColor: "var(--admin-card-bg)",
      }}
    >
      <div className="flex flex-wrap items-center gap-3">
        <AdminSearchInput
          placeholder="Search name, phone, or order #..."
          value={search}
          onChange={(e) => onSearchChange(e.target.value)}
          onClear={() => onSearchChange("")}
          containerClassName="min-w-[12rem]"
        />
        <div className="flex items-center gap-2 ml-auto">
          <span
            className="text-xs"
            style={{ color: "var(--admin-text-muted)" }}
          >
            {orderCount} order{orderCount !== 1 ? "s" : ""}
          </span>
          <Link
            href="/admin/orders"
            className="inline-flex items-center gap-1.5 rounded-xl border px-3 py-1.5 text-xs font-semibold transition-colors"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-card-bg)",
              color: "var(--admin-text-secondary)",
            }}
          >
            <Package className="h-3.5 w-3.5" strokeWidth={2} />
            All Orders
          </Link>
        </div>
      </div>

      <div className="mt-3">
        <AdminFilterTabs
          activeTab={statusFilter}
          onTabChange={onStatusFilterChange}
          tabs={tabs}
        />
      </div>
    </div>
  );
}

function ShippingEmptyState({
  hasFilter,
  onClear,
}: {
  hasFilter: boolean;
  onClear: () => void;
}) {
  return (
    <AdminCard>
      <AdminEmptyState
        icon={
          <div
            className="flex h-16 w-16 items-center justify-center rounded-2xl"
            style={{ backgroundColor: "var(--admin-bg-subtle)" }}
          >
            <Search
              className="h-8 w-8"
              style={{ color: "var(--admin-text-muted)" }}
              strokeWidth={1.5}
            />
          </div>
        }
        title={hasFilter ? "No matching shipping orders" : "No shipping orders"}
        description={
          hasFilter
            ? "Try clearing your search or status filter to see more orders."
            : "When customers place orders with shipping, they'll show up here for fulfillment."
        }
        action={
          hasFilter ? (
            <AdminButton
              variant="secondary"
              size="md"
              onClick={onClear}
              icon={<X className="h-4 w-4" strokeWidth={2} />}
            >
              Clear filters
            </AdminButton>
          ) : undefined
        }
      />
    </AdminCard>
  );
}
