"use client";

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

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

  async function handleSubmit() {
    setPending(true);
    setError("");
    const result = await submitDraftPo(poId);
    if ("error" in result) {
      setError(result.error);
      setPending(false);
    } else {
      router.refresh();
    }
  }

  return (
    <span className="inline-flex items-center gap-2">
      <button
        onClick={handleSubmit}
        disabled={pending}
        className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-700 disabled:opacity-60 transition-colors"
      >
        {pending ? "Submitting…" : "Submit for Approval"}
      </button>
      {error && <span className="text-xs text-danger-700">{error}</span>}
    </span>
  );
}
