"use client";

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

interface PaymentFailureRedirectProps {
  gatewayPaymentId?: string | null;
  fallbackHomeUrl: string;
  fallbackDashboardUrl: string;
  /** Query flag appended on return; use failed_true for /payment/declined (payment_failed=true). */
  appendStatus: AppendPaymentStatusVariant;
  label: string;
  labelReturnToPrevious: string;
  buttonClassName?: string;
}

/**
 * Failure/declined-style pages: stay visible until click; then resolve target and append hook query flags.
 */
export default function PaymentFailureRedirect({
  gatewayPaymentId,
  fallbackHomeUrl,
  fallbackDashboardUrl,
  appendStatus,
  label,
  labelReturnToPrevious,
  buttonClassName = "w-full text-center rounded-xl bg-red-600 hover:bg-red-700 disabled:opacity-70 text-white px-6 py-3 font-bold transition cursor-pointer",
}: PaymentFailureRedirectProps) {
  const router = useRouter();
  const [hasReturnHint, setHasReturnHint] = useState(false);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (typeof window === "undefined") return;
    try {
      const ft =
        appendStatus.type === "failed"
          ? appendStatus.failureType
          : appendStatus.type === "failed_true"
            ? "declined"
            : "cancelled";
      window.localStorage.setItem("payment_failed", ft);
    } catch {
      // ignore
    }
    const meta = getPaymentReturnMeta();
    const legacy = getPaymentReturnUrl();
    setHasReturnHint(
      Boolean(
        (meta?.returnPath && isSafeInternalPath(meta.returnPath)) ||
          meta?.gatewayPaymentId ||
          gatewayPaymentId ||
          (legacy && isSafeInternalPath(legacy)),
      ),
    );
  }, [appendStatus, gatewayPaymentId]);

  const buttonLabel = hasReturnHint ? labelReturnToPrevious : label;

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

  return (
    <button
      type="button"
      onClick={() => void handleClick()}
      disabled={busy}
      className={buttonClassName}
    >
      {buttonLabel}
    </button>
  );
}
