"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import type { EventApprovalStatus, EventStatus } from "@/lib/types";

export default function EventAdminActions({
  eventId,
  featured,
  status,
  approvalStatus = "approved",
}: {
  eventId: string;
  featured: boolean;
  status: EventStatus;
  approvalStatus?: EventApprovalStatus;
}) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [rejecting, setRejecting] = useState(false);
  const [reason, setReason] = useState("");

  async function post(body: Record<string, unknown>, confirmMsg?: string) {
    if (confirmMsg && !confirm(confirmMsg)) return;
    setError(null);
    setLoading(true);
    const res = await fetch("/api/admin/events", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ eventId, ...body }),
    });
    const data = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) {
      setError(data.error || "Action failed");
      return;
    }
    setRejecting(false);
    setReason("");
    router.refresh();
  }

  if (approvalStatus === "pending" && status !== "cancelled") {
    return (
      <div className="flex flex-col items-end gap-1.5">
        <div className="flex flex-wrap justify-end gap-1.5">
          <a href={`/admin/events/${eventId}/preview`} className="be-act be-act-ghost">
            Preview
          </a>
          <button
            type="button"
            onClick={() => post({ decision: "approve" }, "Approve and publish this event? The organizer is emailed.")}
            disabled={loading}
            className="be-act be-act-ok"
          >
            Approve &amp; publish
          </button>
          <button
            type="button"
            onClick={() => setRejecting((v) => !v)}
            disabled={loading}
            className="be-act be-act-danger"
          >
            Reject
          </button>
        </div>
        {rejecting && (
          <form
            onSubmit={(e) => {
              e.preventDefault();
              post({ decision: "reject", note: reason });
            }}
            className="flex w-full max-w-xs flex-col items-end gap-1.5"
          >
            <textarea
              required
              minLength={3}
              rows={2}
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              placeholder="What must the organizer change? (sent to them)"
              className="be-input w-full text-xs"
            />
            <button type="submit" disabled={loading || reason.trim().length < 3} className="be-act be-act-danger">
              Send rejection
            </button>
          </form>
        )}
        {error && <span className="text-xs text-[color:var(--pill-danger-fg)]">{error}</span>}
      </div>
    );
  }

  return (
    <div className="flex flex-col items-end gap-1">
      <div className="flex flex-wrap justify-end gap-1.5">
        <button
          type="button"
          onClick={() => post({ featured: !featured })}
          disabled={loading}
          className={`be-act ${featured ? "be-act-primary" : "be-act-ghost"}`}
        >
          {featured ? "★ Featured" : "Feature"}
        </button>

        {status === "published" ? (
          <button
            type="button"
            onClick={() =>
              post(
                { status: "draft" },
                "Take this event down? It will be removed from the public site."
              )
            }
            disabled={loading}
            className="be-act be-act-danger"
          >
            Take down
          </button>
        ) : status === "cancelled" ? (
          <span className="be-act be-act-ghost pointer-events-none opacity-70">Cancelled</span>
        ) : (
          <button
            type="button"
            onClick={() => post({ status: "published" })}
            disabled={loading}
            className="be-act be-act-ok"
          >
            Publish
          </button>
        )}
      </div>
      {error && <span className="text-xs text-[color:var(--pill-danger-fg)]">{error}</span>}
    </div>
  );
}
