"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";

export function HelpArticlePublishToggle({
  articleId,
  published,
}: {
  articleId: number;
  published: boolean;
}) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  async function handleToggle() {
    setLoading(true);
    try {
      const res = await fetch(`/api/admin/help/${articleId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ published: !published }),
      });
      if (res.ok) {
        router.refresh();
      } else {
        alert("Failed to update publish status");
      }
    } catch {
      alert("Failed to update publish status");
    } finally {
      setLoading(false);
    }
  }

  return (
    <button
      onClick={handleToggle}
      disabled={loading}
      className={`inline-block px-2 py-0.5 rounded text-xs font-medium transition-colors disabled:opacity-50 ${
        published
          ? "bg-green-500/20 text-green-400 hover:bg-green-500/30"
          : "bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30"
      }`}
    >
      {loading ? "..." : published ? "Published" : "Draft"}
    </button>
  );
}
