"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 PaymentSuccessReturnButtonProps {
  /** From Telr return URL when storage is missing (e.g. new tab). */
  gatewayPaymentId?: string | null;
  fallbackHomeUrl: string;
  fallbackDashboardUrl: string;
  labelContinue: string;
  labelReturnToPrevious: string;
}

/**
 * Primary CTA on /payment/success: no auto-redirect; click runs resolve (storage → API by gateway id → legacy).
 */
export default function PaymentSuccessReturnButton({
  gatewayPaymentId,
  fallbackHomeUrl,
  fallbackDashboardUrl,
  labelContinue,
  labelReturnToPrevious,
}: PaymentSuccessReturnButtonProps) {
  const router = useRouter();
  const [hasReturnHint, setHasReturnHint] = useState(false);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (typeof window === "undefined") return;
    try {
      window.localStorage.setItem("payment_completed", "true");
    } catch {
      // ignore
    }
    const meta = getPaymentReturnMeta();
    const legacy = getPaymentReturnUrl();
    setHasReturnHint(
      Boolean(
        (meta?.returnPath && isSafeInternalPath(meta.returnPath)) ||
          meta?.gatewayPaymentId ||
          gatewayPaymentId ||
          (legacy && isSafeInternalPath(legacy)),
      ),
    );
  }, [gatewayPaymentId]);

  const buttonLabel = hasReturnHint ? labelReturnToPrevious : labelContinue;

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

  return (
    <button
      type="button"
      onClick={() => void handleClick()}
      disabled={busy}
      className="w-full text-center rounded-xl bg-[#0F5132] hover:bg-[#1B7A50] disabled:opacity-70 text-white px-6 py-3 font-bold transition cursor-pointer"
    >
      {buttonLabel}
    </button>
  );
}
