"use client";

import { useState, useMemo, useCallback, useEffect } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import {
  Check,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  MapPin,
  Package,
  X,
} from "lucide-react";
import { markPickupComplete } from "@/actions/pickup";
import { createAdminOrder, type AdminCreateOrderItem } from "@/actions/orders/create-admin-order";
import { formatDate } from "@/lib/format-date";
import AdminBadge from "./design-system/AdminBadge";
import {
  AdminButton,
  AdminSearchInput,
  AdminFilterTabs,
  AdminIconButton,
  useToast,
  AdminInput,
  AdminTextInput,
  AdminSelect,
  EmptyState,
  KPIStat,
} from "./design-system";
import { Skeleton } from "./design-system";

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

type Order = {
  id: string;
  customer_name: string;
  customer_email: string | null;
  customer_phone: string | null;
  stop_id: string | null;
  status: string;
  subtotal: number;
  pickup_complete: boolean;
  pickup_completed_at: string | null;
  pickup_completed_by: string | null;
  created_at: string;
  payment_processor: string | null;
  stops: {
    id?: string;
    city: string;
    state: string;
    date: string;
    brand_id?: string;
  } | null;
  order_items?: OrderItem[];
};

type Stop = {
  id: string;
  city: string;
  state: string;
  date: string;
  brand_id?: string;
};

type AdminOrdersPanelProps = {
  initialOrders: Order[];
  initialStops: Stop[];
  initialProducts?: Array<{ id: string; name: string; price: number; type?: string | null; active?: boolean }>;
  brandId: string | null;
};

type StatusTab = "all" | "pending" | "picked_up";

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

function formatCurrency(amount: number) {
  return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount);
}

// Icon wrappers (lucide-react) — kept compact for inline use.
const MapPinIcon = () => <MapPin className="h-4 w-4" strokeWidth={2} />;
const CheckIcon = () => <Check className="h-4 w-4" strokeWidth={2} />;
const XIcon = () => <X className="h-3 w-3" strokeWidth={2} />;
const ChevronDownIcon = () => <ChevronDown className="h-4 w-4" strokeWidth={2} />;
const ChevronLeftIcon = () => <ChevronLeft className="h-4 w-4" strokeWidth={2} />;
const ChevronRightIcon = () => <ChevronRight className="h-4 w-4" strokeWidth={2} />;

export default function AdminOrdersPanel({
  initialOrders,
  initialStops,
  initialProducts = [],
  brandId,
}: AdminOrdersPanelProps) {
  const { success: showSuccess, error: showError } = useToast();
  const searchParams = useSearchParams();
  const [orders, setOrders] = useState<Order[]>(initialOrders);
  const [stops] = useState<Stop[]>(initialStops);
  const [products] = useState(initialProducts);
  const [search, setSearch] = useState("");
  const [activeTab, setActiveTab] = useState<StatusTab>("all");
  const [selectedStops, setSelectedStops] = useState<string[]>([]);

  // New Order modal state (triggered by ?new=true from dashboard or quick actions)
  const [showNewOrderModal, setShowNewOrderModal] = useState(false);
  const [newOrderCustomerName, setNewOrderCustomerName] = useState("");
  const [newOrderCustomerEmail, setNewOrderCustomerEmail] = useState("");
  const [newOrderCustomerPhone, setNewOrderCustomerPhone] = useState("");
  const [newOrderStopId, setNewOrderStopId] = useState<string>("");
  const [newOrderItems, setNewOrderItems] = useState<Array<{ product_id: string; quantity: number; price: number; fulfillment: "pickup" | "ship" }>>([]);
  const [newOrderSubmitting, setNewOrderSubmitting] = useState(false);
  const [newOrderError, setNewOrderError] = useState<string | null>(null);

  // Open the New Order modal when dashboard links here with ?new=true
  useEffect(() => {
    const init = async () => {
      if (searchParams?.get("new") === "true") {
        setShowNewOrderModal(true);
      }
    };
    init();
  }, [searchParams]);

  // --- New Order (admin manual create) helpers ---
  function openNewOrderModal() {
    setShowNewOrderModal(true);
    setNewOrderError(null);
  }

  function closeNewOrderModal() {
    setShowNewOrderModal(false);
    // reset form
    setNewOrderCustomerName("");
    setNewOrderCustomerEmail("");
    setNewOrderCustomerPhone("");
    setNewOrderStopId("");
    setNewOrderItems([]);
    setNewOrderError(null);
  }

  function addNewOrderItem(productId: string) {
    const prod = products.find((p) => p.id === productId);
    if (!prod) return;
    setNewOrderItems((prev) => [
      ...prev,
      {
        product_id: prod.id,
        quantity: 1,
        price: Number(prod.price),
        fulfillment: "pickup",
      },
    ]);
  }

  function updateNewOrderItem(index: number, patch: Partial<{ quantity: number; price: number; fulfillment: "pickup" | "ship" }>) {
    setNewOrderItems((prev) => prev.map((it, i) => (i === index ? { ...it, ...patch } : it)));
  }

  function removeNewOrderItem(index: number) {
    setNewOrderItems((prev) => prev.filter((_, i) => i !== index));
  }

  const newOrderTotal = newOrderItems.reduce((sum, it) => sum + it.price * it.quantity, 0);

  async function handleCreateAdminOrder() {
    if (!newOrderCustomerName.trim()) {
      setNewOrderError("Customer name is required");
      return;
    }
    if (newOrderItems.length === 0) {
      setNewOrderError("Add at least one product");
      return;
    }

    setNewOrderSubmitting(true);
    setNewOrderError(null);

    const result = await createAdminOrder(brandId, {
      customer_name: newOrderCustomerName.trim(),
      customer_email: newOrderCustomerEmail.trim() || null,
      customer_phone: newOrderCustomerPhone.trim() || null,
      stop_id: newOrderStopId || null,
      items: newOrderItems.map((i) => ({
        product_id: i.product_id,
        quantity: i.quantity,
        price: i.price,
        fulfillment: i.fulfillment,
      })),
    });

    setNewOrderSubmitting(false);

    if (result.success) {
      showSuccess(`Order created: ${result.orderId.slice(0, 8).toUpperCase()}`);
      closeNewOrderModal();
      // Navigate to clean orders list (removes ?new=true and shows the new order after refresh)
      window.location.href = "/admin/orders";
    } else {
      setNewOrderError(result.error ?? "Failed to create order");
    }
  }
  const [showStopDropdown, setShowStopDropdown] = useState(false);
  const [pickingUp, setPickingUp] = useState<string | null>(null);
  const [page, setPage] = useState(0);
  const [selectedOrders, setSelectedOrders] = useState<Set<string>>(new Set());
  const [bulkMarkingUp, setBulkMarkingUp] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const PAGE_SIZE = 20;

  // Simulate loading when orders change
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setIsLoading(true);
    const timer = setTimeout(() => setIsLoading(false), 300);
    return () => clearTimeout(timer);
  }, [page, activeTab, search, selectedStops.length]);

  const filteredOrders = useMemo(() => {
    return orders.filter((order) => {
      if (activeTab === "pending" && order.pickup_complete) return false;
      if (activeTab === "picked_up" && !order.pickup_complete) return false;
      if (selectedStops.length > 0 && order.stop_id && !selectedStops.includes(order.stop_id)) return false;
      if (search.trim()) {
        const s = search.toLowerCase();
        if (!order.customer_name.toLowerCase().includes(s) &&
            !(order.customer_phone ?? "").toLowerCase().includes(s) &&
            !order.id.toLowerCase().includes(s)) return false;
      }
      return true;
    });
  }, [orders, activeTab, selectedStops, search]);

  const totalPages = Math.ceil(filteredOrders.length / PAGE_SIZE);
  const paginatedOrders = filteredOrders.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
  const pendingCount = orders.filter((o) => !o.pickup_complete).length;
  const pickedUpCount = orders.filter((o) => o.pickup_complete).length;

  // Bulk selection
  const toggleSelectAll = useCallback(() => {
    if (selectedOrders.size === paginatedOrders.length) {
      setSelectedOrders(new Set());
    } else {
      setSelectedOrders(new Set(paginatedOrders.map(o => o.id)));
    }
  }, [selectedOrders.size, paginatedOrders]);

  const toggleOrderSelection = useCallback((orderId: string) => {
    setSelectedOrders(prev => {
      const next = new Set(prev);
      if (next.has(orderId)) {
        next.delete(orderId);
      } else {
        next.add(orderId);
      }
      return next;
    });
  }, []);

  function toggleStop(stopId: string) {
    setSelectedStops((prev) =>
      prev.includes(stopId) ? prev.filter((id) => id !== stopId) : [...prev, stopId]
    );
    setPage(0);
  }

  function clearStops() {
    setSelectedStops([]);
    setPage(0);
  }

  async function handleMarkPickup(orderId: string) {
    setPickingUp(orderId);
    const result = await markPickupComplete(orderId, brandId);
    if (result.success) {
      showSuccess("Pickup confirmed", `${result.pickup_completed_at ? 'Order marked as picked up' : 'Success'}`);
      setOrders((prev) =>
        prev.map((o) =>
          o.id === orderId
            ? { ...o, pickup_complete: true, pickup_completed_at: result.pickup_completed_at, pickup_completed_by: result.pickup_completed_by }
            : o
        )
      );
    } else {
      showError("Failed to mark pickup", result.error ?? "Please try again");
    }
    setPickingUp(null);
  }

  async function handleBulkMarkPickup() {
    if (selectedOrders.size === 0) return;

    setBulkMarkingUp(true);
    let successCount = 0;
    let failCount = 0;

    for (const orderId of selectedOrders) {
      const result = await markPickupComplete(orderId, brandId);
      if (result.success) {
        successCount++;
        setOrders((prev) =>
          prev.map((o) =>
            o.id === orderId
              ? { ...o, pickup_complete: true, pickup_completed_at: result.pickup_completed_at, pickup_completed_by: result.pickup_completed_by }
              : o
          )
        );
      } else {
        failCount++;
      }
    }

    setBulkMarkingUp(false);
    setSelectedOrders(new Set());

    if (failCount === 0) {
      showSuccess(`${successCount} order${successCount !== 1 ? 's' : ''} marked as picked up`);
    } else {
      showError("Some orders failed", `${successCount} succeeded, ${failCount} failed`);
    }
  }

  return (
    <>
      <div className="p-4 sm:p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div
            className="flex h-10 w-10 items-center justify-center rounded-xl"
            style={{ backgroundColor: "var(--admin-accent)" }}
          >
            <Package className="h-5 w-5 text-white" strokeWidth={2} />
          </div>
          <div>
            <h2
              className="text-base sm:text-lg font-bold"
              style={{ color: "var(--admin-text-primary)" }}
            >
              Orders
            </h2>
            <p
              className="text-[10px] sm:text-xs"
              style={{ color: "var(--admin-text-muted)" }}
            >
              {filteredOrders.length} order{filteredOrders.length !== 1 ? "s" : ""}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          {brandId && (
            <AdminBadge tone="info">Brand scoped</AdminBadge>
          )}
          <AdminButton
            onClick={openNewOrderModal}
            size="sm"
            className="flex items-center gap-2"
          >
            + New Order
          </AdminButton>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 mb-6">
        <KPIStat
          label="Total"
          value={isLoading ? <Skeleton variant="text" className="w-16 h-8" /> : orders.length}
          tone="default"
        />
        <KPIStat
          label="Pending"
          value={isLoading ? <Skeleton variant="text" className="w-12 h-8" /> : pendingCount}
          tone="warning"
        />
        <KPIStat
          label="Picked Up"
          value={isLoading ? <Skeleton variant="text" className="w-12 h-8" /> : pickedUpCount}
          tone="primary"
        />
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3 mb-6">
        {/* Status Tabs */}
        <AdminFilterTabs
          activeTab={activeTab}
          onTabChange={(value) => { setActiveTab(value as StatusTab); setPage(0); }}
          tabs={[
            { value: "all", label: "All", count: filteredOrders.length },
            { value: "pending", label: "Pending", count: pendingCount },
            { value: "picked_up", label: "Picked Up", count: pickedUpCount },
          ]}
          size="md"
        />

        {/* Search */}
        <AdminSearchInput
          placeholder="Search name, phone, or order #..."
          value={search}
          onChange={(e) => { setSearch(e.target.value); setPage(0); }}
          onClear={() => { setSearch(""); setPage(0); }}
          showClear={true}
        />

        {/* Stop Filter */}
        <div className="relative">
          <button
            onClick={() => setShowStopDropdown(!showStopDropdown)}
            className="flex items-center gap-2 rounded-xl border px-4 py-2.5 text-sm font-medium transition-colors"
            style={
              selectedStops.length > 0
                ? {
                    borderColor: "var(--admin-accent)",
                    backgroundColor: "var(--admin-accent-light)",
                    color: "var(--admin-accent-text)",
                  }
                : {
                    borderColor: "var(--admin-border)",
                    backgroundColor: "var(--admin-card-bg)",
                    color: "var(--admin-text-secondary)",
                  }
            }
          >
            <MapPinIcon />
            <span>Stops</span>
            {selectedStops.length > 0 && (
              <span
                className="rounded-full text-white px-1.5 py-0.5 text-xs font-semibold"
                style={{ backgroundColor: "var(--admin-accent)" }}
              >
                {selectedStops.length}
              </span>
            )}
            <ChevronDownIcon />
          </button>

          {showStopDropdown && (
            <>
              <div className="fixed inset-0 z-10" onClick={() => setShowStopDropdown(false)} />
              <div
                className="absolute right-0 top-full mt-2 z-20 w-72 rounded-xl border shadow-lg"
                style={{
                  borderColor: "var(--admin-border)",
                  backgroundColor: "var(--admin-card-bg)",
                }}
              >
                <div
                  className="flex items-center justify-between border-b px-4 py-3"
                  style={{ borderColor: "var(--admin-border-light)" }}
                >
                  <span
                    className="text-sm font-semibold"
                    style={{ color: "var(--admin-text-primary)" }}
                  >
                    Filter by Stop
                  </span>
                  <button
                    onClick={clearStops}
                    className="text-xs font-medium"
                    style={{ color: "var(--admin-accent)" }}
                  >
                    Clear all
                  </button>
                </div>
                <div className="max-h-64 overflow-y-auto p-2">
                  {stops.map((stop) => (
                    <label
                      key={stop.id}
                      className="flex items-center gap-3 rounded-lg px-3 py-2 cursor-pointer transition-colors"
                      style={{ color: "var(--admin-text-primary)" }}
                    >
                      <input
                        type="checkbox"
                        checked={selectedStops.includes(stop.id)}
                        onChange={() => toggleStop(stop.id)}
                        className="h-4 w-4 rounded"
                        style={{
                          borderColor: "var(--admin-border-strong)",
                          accentColor: "var(--admin-accent)",
                        }}
                      />
                      <div className="flex-1">
                        <span
                          className="text-sm font-medium"
                          style={{ color: "var(--admin-text-primary)" }}
                        >
                          {stop.city}, {stop.state}
                        </span>
                        <span
                          className="ml-2 text-xs"
                          style={{ color: "var(--admin-text-muted)" }}
                        >
                          {formatDate(stop.date)}
                        </span>
                      </div>
                    </label>
                  ))}
                </div>
              </div>
            </>
          )}
        </div>
      </div>

      {/* Selected stop chips */}
      {selectedStops.length > 0 && (
        <div className="flex flex-wrap items-center gap-2 mb-4">
          {selectedStops.map((stopId) => {
            const stop = stops.find((s) => s.id === stopId);
            if (!stop) return null;
            return (
              <span
                key={stopId}
                className="inline-flex items-center gap-1 rounded-full border px-3 py-1 text-xs font-medium"
                style={{
                  backgroundColor: "var(--admin-accent-light)",
                  borderColor: "var(--admin-accent)",
                  color: "var(--admin-accent-text)",
                }}
              >
                {stop.city}, {stop.state}
                <button
                  onClick={() => toggleStop(stopId)}
                  className="ml-1"
                  style={{ color: "var(--admin-accent-hover)" }}
                  aria-label={`Remove ${stop.city}, ${stop.state}`}
                >
                  <XIcon />
                </button>
              </span>
            );
          })}
        </div>
      )}

      {/* Bulk actions bar */}
      {selectedOrders.size > 0 && (
        <div
          className="mb-4 flex items-center justify-between rounded-xl border px-4 py-3"
          style={{
            borderColor: "var(--admin-accent)",
            backgroundColor: "var(--admin-accent-light)",
          }}
        >
          <div className="flex items-center gap-3">
            <span
              className="text-sm font-semibold"
              style={{ color: "var(--admin-accent-text)" }}
            >
              {selectedOrders.size} order{selectedOrders.size !== 1 ? 's' : ''} selected
            </span>
            <button
              onClick={() => setSelectedOrders(new Set())}
              className="text-xs"
              style={{ color: "var(--admin-text-muted)" }}
            >
              Clear
            </button>
          </div>
          <AdminButton
            variant="primary"
            size="sm"
            onClick={handleBulkMarkPickup}
            isLoading={bulkMarkingUp}
            icon={<CheckIcon />}
          >
            Mark All as Picked Up
          </AdminButton>
        </div>
      )}

      {/* Orders Table */}
      {isLoading ? (
        <div
          className="rounded-xl border p-6"
          style={{
            borderColor: "var(--admin-border)",
            backgroundColor: "var(--admin-card-bg)",
          }}
        >
          <div className="space-y-4">
            {Array.from({ length: 5 }).map((_, i) => (
              <div key={i} className="flex items-center gap-4">
                <Skeleton variant="rect" className="h-5 w-5 rounded" />
                <Skeleton variant="text" className="flex-1" />
                <Skeleton variant="text" className="w-24" />
                <Skeleton variant="text" className="w-16" />
              </div>
            ))}
          </div>
        </div>
      ) : paginatedOrders.length === 0 ? (
        <div
          className="rounded-xl border"
          style={{
            borderColor: "var(--admin-border)",
            backgroundColor: "var(--admin-card-bg)",
          }}
        >
          <EmptyState
            icon={<Package className="h-9 w-9" strokeWidth={1.25} />}
            title={orders.length === 0 ? "No orders yet" : "No orders match your filters"}
            description={
              orders.length === 0
                ? "Create your first order to get started."
                : "Try adjusting your filters or clearing your search."
            }
            action={
              orders.length === 0
                ? { label: "Create your first order", href: "/admin/orders?new=true" }
                : undefined
            }
          />
        </div>
      ) : (
        <div
          className="overflow-x-auto rounded-xl border"
          style={{
            borderColor: "var(--admin-border)",
            backgroundColor: "var(--admin-card-bg)",
          }}
        >
          <table className="w-full text-sm min-w-[700px]">
            <thead style={{ backgroundColor: "var(--admin-bg)" }}>
              <tr style={{ borderBottom: "1px solid var(--admin-border)" }}>
                <th className="w-10 px-4 py-3">
                  <input
                    type="checkbox"
                    checked={selectedOrders.size === paginatedOrders.length && paginatedOrders.length > 0}
                    onChange={toggleSelectAll}
                    className="h-4 w-4 rounded cursor-pointer"
                    style={{
                      borderColor: "var(--admin-border-strong)",
                      accentColor: "var(--admin-accent)",
                    }}
                  />
                </th>
                <th
                  className="text-left px-4 py-3 font-semibold text-xs"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  Order
                </th>
                <th
                  className="text-left px-4 py-3 font-semibold text-xs"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  Customer
                </th>
                <th
                  className="text-left px-4 py-3 font-semibold text-xs hidden md:table-cell"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  Stop
                </th>
                <th
                  className="text-left px-4 py-3 font-semibold text-xs hidden lg:table-cell"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  Date
                </th>
                <th
                  className="text-center px-4 py-3 font-semibold text-xs"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  Items
                </th>
                <th
                  className="text-right px-4 py-3 font-semibold text-xs"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  Total
                </th>
                <th
                  className="text-center px-4 py-3 font-semibold text-xs"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  Status
                </th>
              </tr>
            </thead>
            <tbody style={{ borderColor: "var(--admin-border)" }}>
              {paginatedOrders.map((order) => (
                <tr
                  key={order.id}
                  className="transition-colors"
                  style={{ borderTop: "1px solid var(--admin-border-light)" }}
                >
                  <td className="px-4 py-3">
                    <input
                      type="checkbox"
                      checked={selectedOrders.has(order.id)}
                      onChange={() => toggleOrderSelection(order.id)}
                      className="h-4 w-4 rounded cursor-pointer"
                      style={{
                        borderColor: "var(--admin-border-strong)",
                        accentColor: "var(--admin-accent)",
                      }}
                    />
                  </td>
                  <td className="px-4 py-3">
                    <Link
                      href={`/admin/orders/${order.id}`}
                      className="font-mono text-xs"
                      style={{ color: "var(--admin-accent)" }}
                    >
                      {shortId(order.id)}
                    </Link>
                  </td>
                  <td className="px-4 py-3">
                    <div
                      className="font-medium"
                      style={{ color: "var(--admin-text-primary)" }}
                    >
                      {order.customer_name}
                    </div>
                    {order.customer_phone && (
                      <div
                        className="font-mono text-xs"
                        style={{ color: "var(--admin-text-muted)" }}
                      >
                        {order.customer_phone}
                      </div>
                    )}
                  </td>
                  <td className="px-4 py-3 hidden md:table-cell">
                    {order.stops ? (
                      <span
                        className="text-sm"
                        style={{ color: "var(--admin-text-primary)" }}
                      >
                        {order.stops.city}, {order.stops.state}
                      </span>
                    ) : (
                      <span style={{ color: "var(--admin-text-muted)" }}>—</span>
                    )}
                  </td>
                  <td className="px-4 py-3 hidden lg:table-cell">
                    <span
                      className="text-sm"
                      style={{ color: "var(--admin-text-muted)" }}
                    >
                      {formatDate(order.created_at)}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <span
                      className="font-mono text-sm"
                      style={{ color: "var(--admin-text-secondary)" }}
                    >
                      {order.order_items?.length ?? 0}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-right">
                    <span
                      className="font-mono font-semibold"
                      style={{ color: "var(--admin-text-primary)" }}
                    >
                      {formatCurrency(order.subtotal)}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <div className="flex items-center justify-center gap-2">
                      {order.pickup_complete ? (
                        <AdminBadge tone="success" dot>Picked Up</AdminBadge>
                      ) : (
                        <AdminBadge tone="warning" dot>Pending</AdminBadge>
                      )}
                      {order.payment_processor === "square" && (
                        <AdminBadge tone="info">Square</AdminBadge>
                      )}
                      {!order.pickup_complete && (
                        <AdminButton
                          variant="ghost"
                          size="sm"
                          onClick={() => handleMarkPickup(order.id)}
                          disabled={pickingUp === order.id}
                          isLoading={pickingUp === order.id}
                        >
                          {pickingUp === order.id ? "..." : "Pick Up"}
                        </AdminButton>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div
          className="flex items-center justify-between mt-4 pt-4 border-t"
          style={{ borderColor: "var(--admin-border)" }}
        >
          <p
            className="text-xs"
            style={{ color: "var(--admin-text-muted)" }}
          >
            Showing {(page * PAGE_SIZE) + 1} to {Math.min((page + 1) * PAGE_SIZE, filteredOrders.length)} of {filteredOrders.length}
          </p>
          <div className="flex items-center gap-2">
            <AdminIconButton
              variant="secondary"
              size="sm"
              label="Previous page"
              onClick={() => setPage((p) => Math.max(0, p - 1))}
              disabled={page === 0}
              className="!rounded-lg"
            >
              <ChevronLeftIcon />
            </AdminIconButton>
            <span
              className="px-3 text-sm font-medium"
              style={{ color: "var(--admin-text-primary)" }}
            >
              {page + 1} / {totalPages}
            </span>
            <AdminIconButton
              variant="secondary"
              size="sm"
              label="Next page"
              onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))}
              disabled={page >= totalPages - 1}
              className="!rounded-lg"
            >
              <ChevronRightIcon />
            </AdminIconButton>
          </div>
        </div>
      )}
      </div>

      {/* New Order Modal (admin manual entry) - sibling to the main panel content */}
      {showNewOrderModal && (
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={{ backgroundColor: "rgba(26, 24, 20, 0.4)" }}>
        <div
          className="w-full max-w-2xl rounded-2xl border shadow-2xl"
          style={{
            borderColor: "var(--admin-border)",
            backgroundColor: "var(--admin-card-bg)",
          }}
        >
          <div
            className="flex items-center justify-between border-b px-6 py-4"
            style={{ borderColor: "var(--admin-border)" }}
          >
            <div>
              <h3
                className="text-lg font-semibold"
                style={{ color: "var(--admin-text-primary)" }}
              >
                New Order (Admin)
              </h3>
              <p
                className="text-xs"
                style={{ color: "var(--admin-text-muted)" }}
              >
                Manual entry for testing / phone orders
              </p>
            </div>
            <button
              onClick={closeNewOrderModal}
              className="text-2xl leading-none"
              style={{ color: "var(--admin-text-muted)" }}
              aria-label="Close"
            >
              ×
            </button>
          </div>

          <div className="p-6 space-y-5 max-h-[70vh] overflow-auto">
            {newOrderError && (
              <div
                className="rounded-lg border px-4 py-2 text-sm"
                style={{
                  backgroundColor: "var(--admin-danger-soft)",
                  borderColor: "var(--admin-danger-soft)",
                  color: "var(--admin-danger)",
                }}
              >
                {newOrderError}
              </div>
            )}

            {/* Customer */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <AdminInput label="Customer Name" required>
                <AdminTextInput
                  value={newOrderCustomerName}
                  onChange={(e) => setNewOrderCustomerName(e.target.value)}
                  placeholder="Jane Doe"
                />
              </AdminInput>
              <AdminInput label="Email">
                <AdminTextInput
                  value={newOrderCustomerEmail}
                  onChange={(e) => setNewOrderCustomerEmail(e.target.value)}
                  placeholder="jane@example.com"
                  type="email"
                />
              </AdminInput>
              <AdminInput label="Phone">
                <AdminTextInput
                  value={newOrderCustomerPhone}
                  onChange={(e) => setNewOrderCustomerPhone(e.target.value)}
                  placeholder="(555) 123-4567"
                />
              </AdminInput>
            </div>

            {/* Stop */}
            <AdminInput label="Pickup Stop (leave blank for ship-only)">
              <AdminSelect
                value={newOrderStopId}
                onChange={(e) => setNewOrderStopId(e.target.value)}
                options={[
                  { value: "", label: "— No stop (ship / manual fulfillment) —" },
                  ...stops.map((s) => ({
                    value: s.id,
                    label: `${s.city}, ${s.state} — ${formatDate(s.date)}`,
                  })),
                ]}
              />
            </AdminInput>

            {/* Items */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <label
                  className="block text-xs font-semibold"
                  style={{ color: "var(--admin-text-secondary)" }}
                >
                  Items
                </label>
                <span
                  className="text-xs"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  Total: ${newOrderTotal.toFixed(2)}
                </span>
              </div>

              {products.length > 0 ? (
                <div className="mb-3">
                  <AdminSelect
                    value=""
                    onChange={(e) => {
                      if (e.target.value) addNewOrderItem(e.target.value);
                    }}
                    options={[
                      { value: "", label: "— Add a product —" },
                      ...products.map((p) => ({ value: p.id, label: `${p.name} — $${Number(p.price).toFixed(2)}` })),
                    ]}
                  />
                </div>
              ) : (
                <p
                  className="text-xs mb-2"
                  style={{ color: "var(--admin-warning)" }}
                >
                  No products loaded for this brand. You can still enter custom items if the action supports it.
                </p>
              )}

              {newOrderItems.length === 0 && (
                <p
                  className="text-xs"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  No items yet. Use the selector above.
                </p>
              )}

              {newOrderItems.length > 0 && (
                <div
                  className="space-y-2 border rounded-xl p-3"
                  style={{
                    borderColor: "var(--admin-border)",
                    backgroundColor: "var(--admin-bg)",
                  }}
                >
                  {newOrderItems.map((item, idx) => {
                    const prod = products.find((p) => p.id === item.product_id);
                    return (
                      <div key={idx} className="grid grid-cols-12 gap-2 items-center text-sm">
                        <div
                          className="col-span-5 font-medium truncate"
                          style={{ color: "var(--admin-text-primary)" }}
                        >
                          {prod?.name ?? item.product_id}
                        </div>
                        <div className="col-span-2">
                          <input
                            type="number"
                            min={1}
                            value={item.quantity}
                            onChange={(e) => updateNewOrderItem(idx, { quantity: Math.max(1, parseInt(e.target.value) || 1) })}
                            className="w-full rounded border px-2 py-1 text-sm"
                            style={{
                              borderColor: "var(--admin-border)",
                              backgroundColor: "var(--admin-card-bg)",
                              color: "var(--admin-text-primary)",
                            }}
                          />
                        </div>
                        <div className="col-span-2">
                          <input
                            type="number"
                            step="0.01"
                            value={item.price}
                            onChange={(e) => updateNewOrderItem(idx, { price: parseFloat(e.target.value) || 0 })}
                            className="w-full rounded border px-2 py-1 text-sm"
                            style={{
                              borderColor: "var(--admin-border)",
                              backgroundColor: "var(--admin-card-bg)",
                              color: "var(--admin-text-primary)",
                            }}
                          />
                        </div>
                        <div className="col-span-2">
                          <select
                            value={item.fulfillment}
                            onChange={(e) => updateNewOrderItem(idx, { fulfillment: e.target.value as "pickup" | "ship" })}
                            className="w-full rounded border px-2 py-1 text-sm"
                            style={{
                              borderColor: "var(--admin-border)",
                              backgroundColor: "var(--admin-card-bg)",
                              color: "var(--admin-text-primary)",
                            }}
                          >
                            <option value="pickup">pickup</option>
                            <option value="ship">ship</option>
                          </select>
                        </div>
                        <div className="col-span-1 text-right">
                          <button
                            type="button"
                            onClick={() => removeNewOrderItem(idx)}
                            className="text-xs hover:underline"
                            style={{ color: "var(--admin-danger)" }}
                          >
                            remove
                          </button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>

          <div
            className="flex items-center justify-end gap-3 border-t px-6 py-4 rounded-b-2xl"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-bg-subtle)",
            }}
          >
            <AdminButton variant="secondary" onClick={closeNewOrderModal} disabled={newOrderSubmitting}>
              Cancel
            </AdminButton>
            <AdminButton onClick={handleCreateAdminOrder} disabled={newOrderSubmitting || newOrderItems.length === 0}>
              {newOrderSubmitting ? "Creating..." : `Create Order — $${newOrderTotal.toFixed(2)}`}
            </AdminButton>
          </div>
        </div>
      </div>
    )}
    </>
  );
}
