"use client";

import { useReducer, useEffect, useTransition } from "react";
import { useRouter } from "next/navigation";
import {
  type WholesaleOrder,
  getWholesalePickupOrders,
  markWholesaleOrderFulfilled,
} from "@/actions/wholesale";
import { wholesaleEmployeeLogoutAction } from "@/actions/wholesale-auth";
import { openHtmlInPopup } from "@/lib/safe-window";
import DepositModal from "@/components/wholesale/DepositModal";
import OrderDetailsModal from "@/components/wholesale/OrderDetailsModal";

type Props = {
  brandId: string;
  brandName: string;
  employeeName: string;
  initialOrders: WholesaleOrder[];
};

type Queue = "past_due" | "today" | "upcoming";

const STATUS_BADGE_MAP: Record<string, string> = {
  pending: "bg-yellow-100 text-yellow-700",
  awaiting_deposit: "bg-purple-100 text-purple-700",
  confirmed: "bg-blue-100 text-blue-700",
  fulfilled: "bg-green-100 text-green-700",
  cancelled: "bg-red-100 text-red-700",
};

type Msg = { kind: "success" | "error"; text: string };

type State = {
  orders: WholesaleOrder[];
  activeTab: Queue;
  showViewOrder: WholesaleOrder | null;
  showDepForm: string | null;
  fulfilling: string | null;
  openActions: string | null;
  msg: Msg | null;
};

type Action =
  | { type: "SET_ORDERS"; orders: WholesaleOrder[] }
  | { type: "SET_ACTIVE_TAB"; tab: Queue }
  | { type: "SET_SHOW_VIEW_ORDER"; order: WholesaleOrder | null }
  | { type: "SET_SHOW_DEP_FORM"; id: string | null }
  | { type: "SET_FULFILLING"; id: string | null }
  | { type: "TOGGLE_ACTIONS"; id: string }
  | { type: "CLOSE_ACTIONS" }
  | { type: "SET_MSG"; msg: Msg }
  | { type: "CLEAR_MSG" };

const initialState = (initialOrders: WholesaleOrder[]): State => ({
  orders: initialOrders,
  activeTab: "today",
  showViewOrder: null,
  showDepForm: null,
  fulfilling: null,
  openActions: null,
  msg: null,
});

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_ORDERS":
      return { ...state, orders: action.orders };
    case "SET_ACTIVE_TAB":
      return { ...state, activeTab: action.tab };
    case "SET_SHOW_VIEW_ORDER":
      return { ...state, showViewOrder: action.order };
    case "SET_SHOW_DEP_FORM":
      return { ...state, showDepForm: action.id };
    case "SET_FULFILLING":
      return { ...state, fulfilling: action.id };
    case "TOGGLE_ACTIONS":
      return {
        ...state,
        openActions: state.openActions === action.id ? null : action.id,
      };
    case "CLOSE_ACTIONS":
      return { ...state, openActions: null };
    case "SET_MSG":
      return { ...state, msg: action.msg };
    case "CLEAR_MSG":
      return { ...state, msg: null };
  }
}

const TAB_STYLES: Record<Queue, { activeBorder: string; activeText: string; countBg: string; countText: string }> = {
  past_due: {
    activeBorder: "border-red-500",
    activeText: "text-red-700",
    countBg: "bg-red-100",
    countText: "text-red-700",
  },
  today: {
    activeBorder: "border-yellow-500",
    activeText: "text-yellow-700",
    countBg: "bg-yellow-100",
    countText: "text-yellow-700",
  },
  upcoming: {
    activeBorder: "border-blue-500",
    activeText: "text-blue-700",
    countBg: "bg-blue-100",
    countText: "text-blue-700",
  },
};

function StatusBadge({ status }: { status: string }) {
  return (
    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_BADGE_MAP[status] ?? "bg-slate-100 text-slate-600"}`}>
      {status.replace(/_/g, " ")}
    </span>
  );
}

export default function EmployeePortalClient({ brandId, brandName, employeeName, initialOrders }: Props) {
  const router = useRouter();
  const [state, dispatch] = useReducer(reducer, initialState(initialOrders));
  const [, startTransition] = useTransition();

  // Close dropdown when clicking outside
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (!(e.target as Element).closest(".actions-cell")) {
        dispatch({ type: "CLOSE_ACTIONS" });
      }
    }
    document.addEventListener("click", handleClick);
    return () => document.removeEventListener("click", handleClick);
  }, []);

  const today = new Date().toISOString().split("T")[0];

  const pastDue = state.orders.filter((o) => o.anticipated_pickup_date && o.anticipated_pickup_date < today);
  const todayOrders = state.orders.filter((o) => o.anticipated_pickup_date === today);
  const upcoming = state.orders.filter((o) => o.anticipated_pickup_date && o.anticipated_pickup_date > today);

  const tabData: Record<Queue, { label: string; orders: WholesaleOrder[] }> = {
    past_due: { label: "Past Due", orders: pastDue },
    today: { label: "Today", orders: todayOrders },
    upcoming: { label: "Upcoming", orders: upcoming },
  };

  const currentTab = tabData[state.activeTab];

  async function handleSignOut() {
    startTransition(async () => {
      await wholesaleEmployeeLogoutAction();
      router.push("/wholesale/login");
    });
  }

  async function handleFulfill(orderId: string) {
    dispatch({ type: "SET_FULFILLING", id: orderId });
    const result = await markWholesaleOrderFulfilled(orderId);
    dispatch({ type: "SET_FULFILLING", id: null });
    if (result.success) {
      dispatch({ type: "SET_MSG", msg: { kind: "success", text: "Order marked as fulfilled." } });
      const data = await getWholesalePickupOrders(brandId);
      dispatch({ type: "SET_ORDERS", orders: data });
    } else {
      dispatch({ type: "SET_MSG", msg: { kind: "error", text: result.error ?? "Failed to fulfill order." } });
    }
    setTimeout(() => dispatch({ type: "CLEAR_MSG" }), 4000);
  }

  return (
    <div className="min-h-screen bg-slate-100">
      <PortalHeader
        brandName={brandName}
        employeeName={employeeName}
        onSignOut={handleSignOut}
      />

      <QueueTabs
        activeTab={state.activeTab}
        tabData={tabData}
        onChange={(tab) => dispatch({ type: "SET_ACTIVE_TAB", tab })}
      />

      <div className="mx-auto max-w-5xl px-6 py-6">
        <MessageBanner msg={state.msg} />

        {currentTab.orders.length === 0 ? (
          <EmptyQueueState
            label={
              currentTab.label === "Past Due"
                ? "No past due orders"
                : currentTab.label === "Today"
                ? "No pickups scheduled today"
                : "No upcoming pickups"
            }
            description={
              currentTab.label === "Past Due"
                ? "All orders are on schedule. Great work!"
                : currentTab.label === "Today"
                ? "There are no wholesale orders scheduled for pickup today."
                : "You have no upcoming pickups scheduled."
            }
          />
        ) : (
          <OrdersList
            orders={currentTab.orders}
            fulfilling={state.fulfilling}
            openActions={state.openActions}
            onToggleActions={(id) => dispatch({ type: "TOGGLE_ACTIONS", id })}
            onFulfill={handleFulfill}
            onRecordDeposit={(id) => dispatch({ type: "SET_SHOW_DEP_FORM", id })}
            onViewDetails={(order) => dispatch({ type: "SET_SHOW_VIEW_ORDER", order })}
            onSendPriceSheet={(order) => {
              fetch("/api/wholesale/price-sheet", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ customerIds: [order.customer_id], brandId: "" }),
              })
                .then((r) => r.json())
                .then(() => {
                  dispatch({
                    type: "SET_MSG",
                    msg: { kind: "success", text: `Price sheet sent to ${order.company_name}.` },
                  });
                })
                .catch(() => {
                  dispatch({ type: "SET_MSG", msg: { kind: "error", text: "Failed to send price sheet." } });
                });
            }}
            onGenerateManifest={(order) => {
              fetch("/api/wholesale/manifest", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ brandId, orders: [order] }),
              })
                .then((r) => r.text())
                .then((html) => openHtmlInPopup(html));
            }}
          />
        )}
      </div>

      <PortalModals
        state={state}
        dispatch={dispatch}
        brandId={brandId}
        handleFulfill={handleFulfill}
      />
    </div>
  );
}

// ── Portal Header ─────────────────────────────────────────────────────────────
function PortalHeader({
  brandName,
  employeeName,
  onSignOut,
}: {
  brandName: string;
  employeeName: string;
  onSignOut: () => void;
}) {
  return (
    <div className="bg-white border-b border-slate-200 px-4 py-3 sm:px-6 sm:py-4">
      <div className="mx-auto max-w-5xl flex items-center justify-between gap-4">
        <div className="min-w-0">
          <h1 className="text-xl sm:text-2xl font-bold text-slate-900 truncate">Pickup Portal</h1>
          <p className="mt-0.5 text-xs sm:text-sm text-slate-500 truncate">{brandName}</p>
        </div>
        <div className="flex items-center gap-3 shrink-0">
          <span className="text-xs sm:text-sm text-slate-500 hidden sm:inline">{employeeName}</span>
          <button
            type="button"
            onClick={onSignOut}
            className="rounded-xl border border-slate-300 px-3 sm:px-4 py-2 text-xs sm:text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors min-h-[40px]"
          >
            Sign Out
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Queue Tabs ────────────────────────────────────────────────────────────────
function QueueTabs({
  activeTab,
  tabData,
  onChange,
}: {
  activeTab: Queue;
  tabData: Record<Queue, { label: string; orders: WholesaleOrder[] }>;
  onChange: (tab: Queue) => void;
}) {
  return (
    <div className="bg-white border-b border-slate-200 px-4 sm:px-6">
      <div className="mx-auto max-w-5xl">
        <nav className="flex gap-1 -mb-px overflow-x-auto">
          {(["past_due", "today", "upcoming"] as Queue[]).map((tab) => {
            const data = tabData[tab];
            const isActive = activeTab === tab;
            const styles = TAB_STYLES[tab];
            return (
              <button
                key={tab}
                type="button"
                onClick={() => onChange(tab)}
                className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 ${
                  isActive
                    ? `${styles.activeBorder} ${styles.activeText}`
                    : "border-transparent text-slate-500 hover:text-slate-700"
                }`}
              >
                {data.label}
                <span className={`rounded-full px-2 py-0.5 text-xs font-bold ${styles.countBg} ${styles.countText}`}>
                  {data.orders.length}
                </span>
              </button>
            );
          })}
        </nav>
      </div>
    </div>
  );
}

// ── Message Banner ────────────────────────────────────────────────────────────
function MessageBanner({ msg }: { msg: Msg | null }) {
  if (!msg) return null;
  return (
    <div
      className={`mb-4 rounded-xl border px-4 py-3 text-sm ${
        msg.kind === "success"
          ? "border-green-200 bg-green-50 text-green-700"
          : "border-red-200 bg-red-50 text-red-700"
      }`}
    >
      {msg.text}
    </div>
  );
}

// ── Orders List ───────────────────────────────────────────────────────────────
type OrdersListProps = {
  orders: WholesaleOrder[];
  fulfilling: string | null;
  openActions: string | null;
  onToggleActions: (id: string) => void;
  onFulfill: (id: string) => void;
  onRecordDeposit: (id: string) => void;
  onViewDetails: (order: WholesaleOrder) => void;
  onGenerateManifest: (order: WholesaleOrder) => void;
  onSendPriceSheet: (order: WholesaleOrder) => void;
};

function OrdersList({
  orders,
  fulfilling,
  openActions,
  onToggleActions,
  onFulfill,
  onRecordDeposit,
  onViewDetails,
  onGenerateManifest,
  onSendPriceSheet,
}: OrdersListProps) {
  return (
    <div className="space-y-3">
      {orders.map((order) => (
        <OrderCard
          key={order.id}
          order={order}
          fulfilling={fulfilling}
          openActions={openActions}
          onToggleActions={() => onToggleActions(order.id)}
          onFulfill={() => onFulfill(order.id)}
          onRecordDeposit={() => onRecordDeposit(order.id)}
          onViewDetails={() => onViewDetails(order)}
          onGenerateManifest={() => onGenerateManifest(order)}
          onSendPriceSheet={() => onSendPriceSheet(order)}
        />
      ))}
    </div>
  );
}

// ── Portal Modals ─────────────────────────────────────────────────────────────
function PortalModals({
  state,
  dispatch,
  brandId,
  handleFulfill,
}: {
  state: State;
  dispatch: React.Dispatch<Action>;
  brandId: string;
  handleFulfill: (orderId: string) => void;
}) {
  const depositOrder = state.showDepForm
    ? state.orders.find((o) => o.id === state.showDepForm) ?? null
    : null;

  return (
    <>
      {state.showViewOrder && (
        <OrderDetailsModal
          order={state.showViewOrder}
          onClose={() => dispatch({ type: "SET_SHOW_VIEW_ORDER", order: null })}
          onFulfill={handleFulfill}
          onRecordDeposit={(id) => {
            dispatch({ type: "SET_SHOW_VIEW_ORDER", order: null });
            dispatch({ type: "SET_SHOW_DEP_FORM", id });
          }}
          fulfilling={state.fulfilling}
        />
      )}

      {depositOrder && (
        <DepositModal
          order={depositOrder}
          onClose={() => dispatch({ type: "SET_SHOW_DEP_FORM", id: null })}
          onFulfilled={async () => {
            dispatch({ type: "SET_MSG", msg: { kind: "success", text: "Deposit recorded." } });
            const data = await getWholesalePickupOrders(brandId);
            dispatch({ type: "SET_ORDERS", orders: data });
          }}
        />
      )}
    </>
  );
}

// ── Loading Skeleton ──────────────────────────────────────────────────────────
function EmployeePortalSkeleton() {
  return (
    <div className="min-h-screen bg-slate-100">
      <div className="bg-white border-b border-slate-200 px-6 py-4">
        <div className="mx-auto max-w-5xl flex items-center justify-between">
          <div className="space-y-2 animate-pulse">
            <div className="h-7 w-40 bg-slate-200 rounded" />
            <div className="h-4 w-32 bg-slate-100 rounded" />
          </div>
          <div className="h-10 w-24 bg-slate-200 rounded-xl" />
        </div>
      </div>
      <div className="bg-white border-b border-slate-200 px-6">
        <div className="mx-auto max-w-5xl">
          <div className="flex gap-1 -mb-px py-3">
            {[1, 2, 3].map((i) => (
              <div key={i} className="h-9 w-20 bg-slate-200 rounded-xl animate-pulse" />
            ))}
          </div>
        </div>
      </div>
      <div className="mx-auto max-w-5xl px-6 py-6 space-y-3">
        {[1, 2, 3, 4].map((i) => (
          <div key={i} className="rounded-2xl bg-white p-5 shadow-sm ring-1 ring-slate-200 animate-pulse">
            <div className="flex items-start justify-between gap-4">
              <div className="space-y-2 flex-1">
                <div className="h-5 w-40 bg-slate-200 rounded" />
                <div className="h-4 w-56 bg-slate-100 rounded" />
                <div className="h-3 w-32 bg-slate-100 rounded" />
              </div>
              <div className="flex gap-2">
                <div className="h-9 w-16 bg-slate-200 rounded-xl" />
                <div className="h-9 w-16 bg-slate-200 rounded-xl" />
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Empty State ──────────────────────────────────────────────────────────────
function EmptyQueueState({ label, description }: { label: string; description: string }) {
  return (
    <div className="rounded-2xl bg-white p-12 text-center shadow-sm ring-1 ring-slate-200">
      <div className="w-16 h-16 bg-slate-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
        <svg className="w-8 h-8 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"/>
        </svg>
      </div>
      <p className="text-lg font-semibold text-slate-700 mb-2">{label}</p>
      <p className="text-sm text-slate-500 max-w-xs mx-auto">{description}</p>
    </div>
  );
}

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

function OrderCard({
  order,
  fulfilling,
  openActions,
  onToggleActions,
  onFulfill,
  onRecordDeposit,
  onViewDetails,
  onGenerateManifest,
  onSendPriceSheet,
}: {
  order: WholesaleOrder;
  fulfilling: string | null;
  openActions: string | null;
  onToggleActions: () => void;
  onFulfill: (id: string) => void;
  onRecordDeposit: () => void;
  onViewDetails: () => void;
  onGenerateManifest: () => void;
  onSendPriceSheet?: () => void;
}) {
  const hasPhone = Boolean(order.customer_phone);

  return (
    <div className="rounded-2xl bg-white shadow-sm ring-1 ring-slate-200 overflow-hidden hover:ring-slate-300 transition-shadow">
      {/* Card header */}
      <div className="px-4 py-4 sm:px-5 sm:py-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
        <div className="flex-1 min-w-0 w-full">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="font-semibold text-slate-900 text-sm sm:text-base">{order.company_name}</span>
            <StatusBadge status={order.status} />
            <span className={`text-xs font-medium ${order.payment_status === "paid" ? "text-green-600" : "text-orange-600"}`}>
              {order.payment_status === "paid" ? "Paid" : `$${Number(order.balance_due).toFixed(2)} due`}
            </span>
          </div>
          <p className="text-xs sm:text-sm text-slate-500 mt-0.5">
            {order.contact_name ?? ""}
            {hasPhone ? (
              <> · <a href={`tel:${order.customer_phone}`} className="hover:underline">{order.customer_phone}</a></>
            ) : (
              <> · <a href={`mailto:${order.customer_email}`} className="hover:underline">{order.customer_email}</a></>
            )}
          </p>
          <p className="text-xs text-slate-400 mt-0.5">
            {order.invoice_number ?? order.id.slice(0, 8)} · Pickup: {order.anticipated_pickup_date ?? "—"}
          </p>
        </div>

        {/* Inline action buttons */}
        <div className="flex items-center gap-2 shrink-0 w-full sm:w-auto justify-end">
          {order.fulfillment_status !== "fulfilled" && (
            <button
              type="button"
              onClick={() => !fulfilling && onFulfill(order.id)}
              disabled={fulfilling === order.id}
              title="Mark as fulfilled"
              className="inline-flex items-center gap-1.5 rounded-xl bg-green-600 px-3 py-2 text-xs font-bold text-white shadow-sm hover:bg-green-700 disabled:opacity-40 transition-colors"
            >
              <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" /></svg>
              {fulfilling === order.id ? "..." : "Fulfill"}
            </button>
          )}
          {Number(order.balance_due) > 0 && order.fulfillment_status !== "fulfilled" && (
            <button aria-label="Record deposit"
              type="button"
              onClick={onRecordDeposit} title="Record deposit"
              className="inline-flex items-center gap-1.5 rounded-xl bg-purple-600 px-3 py-2 text-xs font-bold text-white shadow-sm hover:bg-purple-700 transition-colors">
              <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 6v12m-9-9h18" /></svg>
              Deposit
            </button>
          )}
          <a aria-label="Download Invoice (PDF)"
            href={`/api/wholesale/invoice/${order.id}/pdf`}
            target="_blank"
            rel="noopener noreferrer" title="Download Invoice (PDF)"
            className="inline-flex items-center justify-center rounded-xl w-9 h-9 text-slate-500 hover:text-slate-800 hover:bg-slate-100 transition-colors">
            <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12h9m-9-6h6m-3 12a9 9 0 110 12H15M6 2h9l4 4v14a2 2 0 01-2 2H6a2 2 0 01-2-2V4a2 2 0 012-2z"/></svg>
          </a>
          <div className="relative">
            <button aria-label="More actions"
              type="button"
              onClick={onToggleActions} title="More actions"
              className="inline-flex items-center justify-center rounded-xl w-9 h-9 text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors">
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><circle cx="10" cy="4" r="1.5"/><circle cx="10" cy="10" r="1.5"/><circle cx="10" cy="16" r="1.5"/></svg>
            </button>
            {openActions === order.id && (
              <div
                className="absolute bottom-full right-0 mb-1 z-30 w-56 rounded-xl bg-white shadow-xl ring-1 ring-slate-200 py-1 text-sm"
                onClick={(e) => e.stopPropagation()}
              >
                <button type="button" onClick={() => { onToggleActions(); onViewDetails(); }} className="w-full text-left px-4 py-3 text-slate-700 hover:bg-slate-50 flex items-center gap-3">
                  <svg className="w-4 h-4 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                  View Details
                </button>
                <button type="button" onClick={() => { onToggleActions(); onGenerateManifest(); }} className="w-full text-left px-4 py-3 text-slate-700 hover:bg-slate-50 flex items-center gap-3">
                  <svg className="w-4 h-4 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12h9m-9-6h6m-3 12a9 9 0 01-18 0 9 9 0 0118 0z"/></svg>
                  Generate Manifest
                </button>
                <div className="my-1 border-t border-slate-100" />
                <button
                  type="button"
                  onClick={() => { onToggleActions(); onSendPriceSheet?.(); }}
                  className="w-full text-left px-4 py-3 text-slate-700 hover:bg-slate-50 flex items-center gap-3"
                >
                  <svg className="w-4 h-4 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
                  Send Price Sheet
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Line items summary */}
      {order.items && order.items.length > 0 && (
        <div className="px-4 pb-4 sm:px-5 sm:pb-4">
          <div className="rounded-xl bg-slate-50 border border-slate-100 overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-slate-100 text-slate-500">
                <tr>
                  <th className="px-4 py-2 text-left font-medium text-xs">Product</th>
                  <th className="px-4 py-2 text-right font-medium text-xs">Qty</th>
                  <th className="px-4 py-2 text-right font-medium text-xs">Total</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {order.items.map((item, i) => (
                  <tr key={item.id ?? i}>
                    <td className="px-4 py-2 text-slate-700 text-xs">{item.product_name}</td>
                    <td className="px-4 py-2 text-right text-slate-600 text-xs">{item.quantity}</td>
                    <td className="px-4 py-2 text-right font-medium text-slate-900 text-xs">${Number(item.line_total).toFixed(2)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}