"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { useConfirmDialog } from "@/components/ui/confirm-dialog";
import { clientFetch } from "@/lib/api/client";

export function EventActions({
  eventId,
  status,
  basePath = "/admin/events",
}: {
  eventId: number;
  status: string;
  /** Where to redirect after duplicate/delete — lets `/admin/signature/events/*` reuse this without landing back in the general Event admin. */
  basePath?: string;
}) {
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const [isPublishing, setIsPublishing] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isDuplicating, setIsDuplicating] = useState(false);
  const { confirm, dialog } = useConfirmDialog();

  async function handlePublish() {
    setError(null);
    setIsPublishing(true);
    const res = await clientFetch(`/api/admin/events/${eventId}/publish`, { method: "POST" });
    setIsPublishing(false);

    const body = await res.json().catch(() => null);
    if (!res.ok) {
      setError(body?.message ?? "Failed to publish event.");
      return;
    }
    router.refresh();
  }

  async function handleDuplicate() {
    setError(null);
    setIsDuplicating(true);
    const res = await clientFetch(`/api/admin/events/${eventId}/duplicate`, { method: "POST" });
    setIsDuplicating(false);

    const body = await res.json().catch(() => null);
    if (!res.ok) {
      setError(body?.message ?? "Failed to duplicate event.");
      return;
    }
    router.push(`${basePath}/${body.data.id}`);
    router.refresh();
  }

  async function handleDelete() {
    if (!(await confirm("Delete this event? This action cannot be undone."))) return;

    setError(null);
    setIsDeleting(true);
    const res = await clientFetch(`/api/admin/events/${eventId}`, { method: "DELETE" });
    setIsDeleting(false);

    const body = await res.json().catch(() => null);
    if (!res.ok) {
      setError(body?.message ?? "Failed to delete event.");
      return;
    }
    router.push(basePath);
    router.refresh();
  }

  return (
    <div className="flex flex-col gap-2">
      {dialog}
      <div className="flex flex-wrap gap-2">
        {status === "draft" && (
          <Button type="button" onClick={handlePublish} disabled={isPublishing}>
            {isPublishing ? "Publishing..." : "Publish"}
          </Button>
        )}
        <Button type="button" variant="secondary" onClick={handleDuplicate} disabled={isDuplicating}>
          {isDuplicating ? "Duplicating..." : "Duplicate as Template"}
        </Button>
        <Button type="button" variant="danger" onClick={handleDelete} disabled={isDeleting}>
          {isDeleting ? "Deleting..." : "Delete Event"}
        </Button>
      </div>
      {error && <p className="text-sm text-red-600">{error}</p>}
    </div>
  );
}
