"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { navigateAfterPaymentResult } from "@/lib/payment-return-resolve";
import {
  getPaymentReturnMeta,
  getPaymentReturnUrl,
  isSafeInternalPath,
} from "@/lib/payment-return";

interface PaymentCancelledReturnButtonProps {
  gatewayPaymentId?: string | null;
  fallbackHomeUrl: string;
  fallbackDashboardUrl: string;
  label: string;
  labelReturnToPrevious: string;
}

/** /payment/cancelled manual return with payment_cancelled=true for page hooks. */
export default function PaymentCancelledReturnButton({
  gatewayPaymentId,
  fallbackHomeUrl,
  fallbackDashboardUrl,
  label,
  labelReturnToPrevious,
}: PaymentCancelledReturnButtonProps) {
  const router = useRouter();
  const [hasReturnHint, setHasReturnHint] = useState(false);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    const meta = getPaymentReturnMeta();
    const legacy = getPaymentReturnUrl();
    setHasReturnHint(
      Boolean(
        (meta?.returnPath && isSafeInternalPath(meta.returnPath)) ||
          meta?.gatewayPaymentId ||
          gatewayPaymentId ||
          (legacy && isSafeInternalPath(legacy)),
      ),
    );
  }, [gatewayPaymentId]);

  const buttonLabel = hasReturnHint ? labelReturnToPrevious : label;

  const handleClick = async () => {
    if (busy) return;
    setBusy(true);
    try {
      await navigateAfterPaymentResult(router, {
        gatewayPaymentIdFromUrl: gatewayPaymentId,
        appendStatus: { type: "cancelled_query" },
        fallbackHomeUrl,
        fallbackDashboardUrl,
      });
    } finally {
      setBusy(false);
    }
  };

  return (
    <button
      type="button"
      onClick={() => void handleClick()}
      disabled={busy}
      className="w-full text-center rounded-xl border border-slate-200 hover:border-slate-300 disabled:opacity-70 text-slate-800 bg-white/70 px-6 py-3 font-bold transition cursor-pointer"
    >
      {buttonLabel}
    </button>
  );
}
