"use client";

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

export function RegistrationSupportActions({
  registrationId,
  registrationStatus,
}: {
  registrationId: string;
  registrationStatus: string;
}) {
  const router = useRouter();
  const [bookingStatus, setBookingStatus] = useState(registrationStatus);
  const [cancellationReason, setCancellationReason] = useState("");
  const [busy, setBusy] = useState("");
  const [message, setMessage] = useState("");
  const [isError, setIsError] = useState(false);
  const [refundPaymentId, setRefundPaymentId] = useState<string | null>(null);

  const callApi = async (
    key: string,
    url: string,
    options: RequestInit,
  ) => {
    setBusy(key);
    setMessage("");
    setIsError(false);

    try {
      const response = await fetch(url, options);
      const payload = (await response.json()) as {
        error?: string;
        refundPaymentId?: string | null;
        cancellationNoticeQueued?: boolean;
      };

      if (!response.ok) {
        throw new Error(
          payload.error ||
            "The support action could not be completed.",
        );
      }

      setRefundPaymentId(payload.refundPaymentId || null);
      setMessage(
        payload.refundPaymentId
          ? "Booking cancelled. A customer notice was queued and the payment needs refund review."
          : payload.cancellationNoticeQueued
            ? "Booking cancelled and the customer notice was queued."
            : "Support action saved.",
      );
      router.refresh();
    } catch (error) {
      setIsError(true);
      setMessage(
        error instanceof Error
          ? error.message
          : "The support action could not be completed.",
      );
    } finally {
      setBusy("");
    }
  };

  const jsonOptions = (
    payload: Record<string, unknown>,
    method = "PATCH",
  ): RequestInit => ({
    method,
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(payload),
  });

  const updateBooking = () => {
    if (bookingStatus === "cancelled" && cancellationReason.trim().length < 3) {
      setIsError(true);
      setMessage("Add a short cancellation reason before saving.");
      return;
    }
    return callApi(
      "booking",
      `/api/admin/registrations/${registrationId}`,
      jsonOptions({
        status: bookingStatus,
        reason: bookingStatus === "cancelled" ? cancellationReason : undefined,
      }),
    );
  };

  return (
    <div className="space-y-5">
      <section className="rounded-2xl border border-slate-200/80 bg-white p-6 shadow-xs">
        <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-[#F97316]">
          Booking action
        </p>

        <h2 className="mt-1 text-lg font-bold tracking-tight text-[#0D1B2A]">
          Keep the roster accurate
        </h2>

        <div className="mt-4 flex gap-2">
          <select
            value={bookingStatus}
            onChange={(event) =>
              setBookingStatus(event.target.value)
            }
            className="h-10 min-w-0 flex-1 rounded-xl border border-slate-200/80 bg-white px-3 text-xs font-semibold text-[#0D1B2A] outline-none transition focus:border-[#1D4ED8] focus:ring-2 focus:ring-[#1D4ED8]/20"
          >
            <option value="pending">Pending</option>
            <option value="confirmed">Confirmed</option>
            <option value="waitlisted">Waitlisted</option>
            <option value="cancelled">Cancelled</option>
          </select>

          <button
            type="button"
            disabled={Boolean(busy)}
            onClick={updateBooking}
            className="rounded-xl bg-[#1D4ED8] px-4 text-xs font-semibold text-white shadow-xs transition hover:bg-[#1e40af] disabled:opacity-50"
          >
            {busy === "booking" ? "Saving..." : "Update"}
          </button>
        </div>

        {bookingStatus === "cancelled" && (
          <label className="mt-4 block text-xs font-semibold text-slate-700">
            Cancellation reason
            <textarea
              required
              minLength={3}
              maxLength={1000}
              value={cancellationReason}
              onChange={(event) => setCancellationReason(event.target.value)}
              placeholder="Explain what the customer should be told"
              className="mt-2 min-h-24 w-full rounded-xl border border-slate-200/80 bg-white px-3 py-2.5 text-xs font-medium outline-none transition focus:border-[#1D4ED8] focus:ring-2 focus:ring-[#1D4ED8]/20"
            />
          </label>
        )}

        <p className="mt-3 text-xs leading-5 text-slate-500">
          Cancelling a booking keeps the historical payment record. Paid bookings are sent to refund review; no refund is issued automatically.
        </p>

        {refundPaymentId && (
          <Link href={`/admin/payments/${refundPaymentId}`} className="mt-3 inline-flex items-center gap-1.5 text-xs font-extrabold text-[#a45209] hover:text-[#102630]">
            Review refund
            <span className="material-symbols-outlined text-[16px]">arrow_forward</span>
          </Link>
        )}

        {message && (
          <p
            className={`mt-4 text-xs font-bold ${
              isError
                ? "text-[#9a4338]"
                : "text-[#246845]"
            }`}
          >
            {message}
          </p>
        )}
      </section>
    </div>
  );
}
