"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { RefreshCw, RotateCcw } from "lucide-react";
import toast from "react-hot-toast";

export default function AdminCJSyncButton() {
  const router = useRouter();
  const [busy, setBusy] = useState<"sync" | "retry" | null>(null);

  const run = async (action: "sync" | "retry") => {
    setBusy(action);
    try {
      const res = await fetch("/api/admin/orders/sync", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action }),
      });
      const data = await res.json();

      if (!res.ok) {
        toast.error(data.error ?? "CJ sync failed.");
        return;
      }

      if (action === "retry") {
        toast.success(
          data.forwarded > 0
            ? `${data.forwarded} order(s) forwarded to CJ.`
            : "No failed orders were ready to retry."
        );
      } else {
        toast.success(
          `Checked ${data.checked} order(s) — ${data.withTracking} with tracking.`
        );
        if (data.errors?.length) {
          toast.error(`${data.errors.length} order(s) returned an error from CJ.`);
        }
      }
      router.refresh();
    } catch {
      toast.error("Could not reach the sync endpoint.");
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="flex items-center gap-2">
      <button
        onClick={() => run("retry")}
        disabled={busy !== null}
        className="btn-outline text-xs px-3 py-2 disabled:opacity-60"
        title="Re-send orders that failed to reach CJ"
      >
        <RotateCcw className={`h-3.5 w-3.5 ${busy === "retry" ? "animate-spin" : ""}`} />
        Retry failed
      </button>
      <button
        onClick={() => run("sync")}
        disabled={busy !== null}
        className="btn-primary text-xs px-3 py-2 disabled:opacity-60"
        title="Pull the latest status and tracking numbers from CJ"
      >
        <RefreshCw className={`h-3.5 w-3.5 ${busy === "sync" ? "animate-spin" : ""}`} />
        {busy === "sync" ? "Syncing..." : "Sync CJ tracking"}
      </button>
    </div>
  );
}
