"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { enqueueAction } from "@/lib/offline/queue";
import { syncPending } from "@/lib/offline/sync";
import { dispatchClientAction } from "@/actions/offline-dispatcher";

interface OrderActionButtonsProps {
  orderId: string;
  status: "placed" | "ready" | "picked-up" | "cancelled";
}

/**
 * Sticky action bar buttons for the v2 order detail page.
 *
 * Maps the v2 status vocabulary to the v2 action vocabulary:
 *   - placed   → enqueue "markOrderReady"      → backend: toggle pickup_complete=false
 *   - ready    → enqueue "markOrderPickedUp"   → backend: toggle pickup_complete=true
 *   - picked-up → render "View Receipt" (outlined) — links to the v1 receipt page
 *   - cancelled → render the "View Receipt" fallback (no primary action)
 *
 * The action is enqueued to IndexedDB and replayed via the
 * `syncPending` engine, which calls `dispatchClientAction` for each
 * pending record. The StickyActionBar's `pendingSync` badge is shown
 * while the queue has work, and the page is `router.refresh()`-ed on
 * success so the server component re-renders with the new status.
 *
 * NOTE: the dispatcher (`src/actions/offline-dispatcher.ts`) currently
 * returns "Unknown action" for both markOrderReady and markOrderPickedUp
 * because the matching server actions don't ship in PR 3. The UI
 * surface (queue, conflict, refresh) is in place — wiring the real
 * handlers is a follow-up. Until then, clicks will surface in the
 * OfflineBanner's "failed" count and the user sees a brief "Marking…"
 * state. This matches the plan: PR 3 is structure, not the full
 * happy path.
 */
export function OrderActionButtons({ orderId, status }: OrderActionButtonsProps) {
  const router = useRouter();
  const [pending, setPending] = useState(false);
  const [conflict, setConflict] = useState<string | null>(null);
  const [pendingSync, setPendingSync] = useState(false);

  async function handleAction(actionName: string) {
    setPending(true);
    setConflict(null);
    setPendingSync(true);
    try {
      await enqueueAction(actionName, { orderId });
      const result = await syncPending(
        (name, payload, id) => dispatchClientAction(name, payload, id),
        { online: navigator.onLine, sleep: (ms) => new Promise((r) => setTimeout(r, ms)) },
      );
      if (result.conflicts > 0) {
        setConflict("This order changed elsewhere. Refresh to see the latest.");
      } else if (result.synced > 0) {
        // Successful replay — the server invalidated the path; pull fresh data.
        router.refresh();
      }
      // result.failed: the action wasn't recognized. The OfflineBanner will
      // surface the failure count; we don't inline an error here.
    } finally {
      setPending(false);
      setPendingSync(false);
    }
  }

  if (conflict) {
    return (
      <div className="text-body" style={{ color: "var(--color-danger)" }}>
        {conflict}
      </div>
    );
  }

  if (status === "placed") {
    return (
      <button
        type="button"
        onClick={() => handleAction("markOrderReady")}
        disabled={pending}
        className="w-full rounded-xl text-label font-semibold active:opacity-80 transition-opacity"
        style={{
          backgroundColor: "var(--color-accent)",
          color: "white",
          minHeight: "56px",
          letterSpacing: "0.02em",
        }}
        data-pending-sync={pendingSync ? "true" : "false"}
      >
        {pending ? "Marking…" : "Mark Ready"}
      </button>
    );
  }

  if (status === "ready") {
    return (
      <button
        type="button"
        onClick={() => handleAction("markOrderPickedUp")}
        disabled={pending}
        className="w-full rounded-xl text-label font-semibold active:opacity-80 transition-opacity"
        style={{
          backgroundColor: "var(--color-accent)",
          color: "white",
          minHeight: "56px",
          letterSpacing: "0.02em",
        }}
        data-pending-sync={pendingSync ? "true" : "false"}
      >
        {pending ? "Marking…" : "Mark Picked Up"}
      </button>
    );
  }

  return (
    <a
      href={`/admin/orders/${orderId}/receipt`}
      className="block w-full text-center rounded-xl text-label font-semibold active:opacity-80 transition-opacity"
      style={{
        border: "1px solid var(--color-surface-3)",
        minHeight: "56px",
        lineHeight: "56px",
        letterSpacing: "0.02em",
      }}
    >
      View Receipt
    </a>
  );
}

export default OrderActionButtons;
