"use client";

import { useState } from "react";
import { toggleProjectPublishAction } from "./actions";
import { Loader2 } from "lucide-react";

export function TogglePublishButton({ id, isPublished }: { id: string; isPublished: boolean }) {
  const [loading, setLoading] = useState(false);

  async function handleToggle() {
    setLoading(true);
    await toggleProjectPublishAction(id, isPublished);
    setLoading(false);
  }

  return (
    <button
      onClick={handleToggle}
      disabled={loading}
      className={`px-3 py-1 rounded-full text-xs font-bold font-mono border transition-all disabled:opacity-50 ${
        isPublished 
          ? "bg-success/10 text-success border-success/30 hover:bg-error/10 hover:text-error hover:border-error/30 group" 
          : "bg-muted/50 text-muted-foreground border-border hover:bg-success/10 hover:text-success hover:border-success/30"
      }`}
    >
      {loading ? (
        <Loader2 size={12} className="animate-spin" />
      ) : isPublished ? (
        <span className="group-hover:hidden">Published</span>
      ) : (
        <span>Draft</span>
      )}
      {isPublished && !loading && <span className="hidden group-hover:inline">Unpublish</span>}
    </button>
  );
}
