"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import type { EventApprovalStatus, EventStatus } from "@/lib/types";

export default function EventStatusToggle({
  eventId,
  status,
  pendingCancellation,
  lastRejection,
  approvalStatus = "approved",
  approvalNote = null,
}: {
  eventId: string;
  status: EventStatus;
  // VibePass review: until "approved", Publish becomes "Submit for review".
  approvalStatus?: EventApprovalStatus;
  approvalNote?: string | null;
  // Set while a cancellation request is awaiting admin review.
  pendingCancellation: { reason: string; createdAt: string } | null;
  // The admin's note on the most recent rejected request, if any.
  lastRejection: { note: string | null } | null;
}) {
  const router = useRouter();
  const [showForm, setShowForm] = useState(false);
  const [reason, setReason] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function setStatus(next: EventStatus) {
    setError(null);
    const res = await fetch(`/api/dashboard/events/${eventId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: next }),
    });
    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      setError(data.error ?? "Could not update the event");
    }
    router.refresh();
  }

  async function requestCancellation(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    const res = await fetch(`/api/dashboard/events/${eventId}/cancellation`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ reason }),
    });
    const data = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) {
      setError(data.error ?? "Could not send the request");
      return;
    }
    setShowForm(false);
    setReason("");
    router.refresh();
  }

  async function withdraw() {
    if (!confirm("Withdraw your cancellation request? The event stays as it is.")) return;
    setError(null);
    setLoading(true);
    const res = await fetch(`/api/dashboard/events/${eventId}/cancellation`, { method: "DELETE" });
    const data = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) setError(data.error ?? "Could not withdraw the request");
    router.refresh();
  }

  if (status === "cancelled") {
    return (
      <span className="rounded-md border border-red-300 px-3 py-1.5 text-sm font-medium text-red-600">
        Cancelled
      </span>
    );
  }

  return (
    <div className="flex flex-col items-end gap-2">
      <div className="flex gap-2">
        {status !== "published" && approvalStatus === "approved" && (
          <button
            onClick={() => setStatus("published")}
            className="rounded-md bg-green-600 text-white px-3 py-1.5 text-sm font-medium hover:bg-green-700"
          >
            Publish
          </button>
        )}
        {(approvalStatus === "unsubmitted" || approvalStatus === "rejected") && (
          <button
            onClick={() => setStatus("published")}
            className="rounded-md bg-green-600 text-white px-3 py-1.5 text-sm font-medium hover:bg-green-700"
          >
            {approvalStatus === "rejected" ? "Resubmit for review" : "Submit for review"}
          </button>
        )}
        {approvalStatus === "pending" && (
          <span className="rounded-md px-3 py-1.5 text-sm font-medium pill-warn">Awaiting VibePass approval</span>
        )}
        {status === "published" && (
          <button
            onClick={() => setStatus("draft")}
            className="rounded-md border border-be-border px-3 py-1.5 text-sm font-medium hover:bg-be-surface-2"
          >
            Unpublish
          </button>
        )}
        {pendingCancellation ? (
          <button
            onClick={withdraw}
            disabled={loading}
            className="rounded-md border border-be-border px-3 py-1.5 text-sm font-medium hover:bg-be-surface-2 disabled:opacity-50"
          >
            Withdraw cancellation request
          </button>
        ) : (
          !showForm && (
            <button
              onClick={() => setShowForm(true)}
              className="rounded-md border border-red-300 text-red-600 px-3 py-1.5 text-sm font-medium hover:bg-red-50"
            >
              Request cancellation
            </button>
          )
        )}
      </div>

      {approvalStatus === "unsubmitted" && (
        <p className="max-w-sm text-right text-xs text-be-muted">
          VibePass reviews every new event before it goes live. Add your ticket types, then submit — you&apos;ll
          get an email once it&apos;s approved.
        </p>
      )}
      {approvalStatus === "pending" && (
        <p className="max-w-sm text-right text-xs text-be-muted">
          Submitted for review. It goes live as soon as VibePass approves it — you&apos;ll get an email.
        </p>
      )}
      {approvalStatus === "rejected" && (
        <p className="max-w-sm text-right text-xs rounded-md px-3 py-2 pill-danger">
          Not approved yet{approvalNote ? `: “${approvalNote}”` : "."} Make the changes, then resubmit.
        </p>
      )}

      {pendingCancellation && (
        <p className="max-w-sm text-right text-xs pill-warn rounded-md px-3 py-2">
          Cancellation requested — awaiting approval from VibePass. Your event stays live and tickets remain
          valid until it&apos;s approved.
        </p>
      )}

      {!pendingCancellation && lastRejection && !showForm && (
        <p className="max-w-sm text-right text-xs text-be-muted">
          Your last cancellation request was declined
          {lastRejection.note ? `: “${lastRejection.note}”` : "."}
        </p>
      )}

      {showForm && (
        <form
          onSubmit={requestCancellation}
          className="w-full max-w-sm space-y-2 rounded-lg border border-be-border bg-be-surface p-3 text-left"
        >
          <p className="text-xs text-be-muted">
            A VibePass admin reviews every cancellation. If approved, the event is cancelled, all tickets
            are voided, and every buyer is queued for a refund.
          </p>
          <textarea
            required
            minLength={5}
            maxLength={1000}
            rows={3}
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            placeholder="Why does this event need to be cancelled?"
            className="input w-full text-sm"
          />
          <div className="flex justify-end gap-2">
            <button
              type="button"
              onClick={() => {
                setShowForm(false);
                setReason("");
              }}
              className="rounded-md border border-be-border px-3 py-1.5 text-sm font-medium hover:bg-be-surface-2"
            >
              Back
            </button>
            <button
              type="submit"
              disabled={loading || reason.trim().length < 5}
              className="rounded-md bg-red-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-red-700 disabled:opacity-50"
            >
              {loading ? "Sending…" : "Send request"}
            </button>
          </div>
        </form>
      )}

      {error && <p className="text-xs text-red-600">{error}</p>}
    </div>
  );
}
