"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { discardDraftPo } from "@/app/(portal)/po/[id]/actions";

export function DiscardDraftButton({ poId }: { poId: string }) {
  const router = useRouter();
  const [pending, setPending] = useState(false);
  const [error, setError] = useState("");

  async function handleDiscard() {
    if (!confirm("Permanently discard this draft? This cannot be undone.")) return;
    setPending(true);
    const result = await discardDraftPo(poId);
    if ("error" in result) {
      setError(result.error);
      setPending(false);
    } else {
      router.push("/my-orders");
    }
  }

  return (
    <span className="relative">
      <button
        type="button"
        onClick={handleDiscard}
        disabled={pending}
        className="rounded-lg border border-danger-200 bg-white px-3 py-2 text-sm font-medium text-danger-600 hover:bg-danger-50 disabled:opacity-60 transition-colors"
      >
        {pending ? "Discarding…" : "Discard"}
      </button>
      {error && (
        <span className="absolute right-0 top-full mt-1 w-56 rounded-lg bg-danger-50 border border-danger-200 px-3 py-2 text-xs text-danger-700 shadow-sm z-10">
          {error}
        </span>
      )}
    </span>
  );
}
