"use client";

import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  InsufficientBalance,
  walletRechargeUrl,
} from "@/app/lib/paidService";

interface Props {
  info: InsufficientBalance;
}

/*
 * Modal shown when a paid astrology service answers INSUFFICIENT_BALANCE.
 * "Recharge wallet" opens the price list with the missing amount pre-filled;
 * closing the modal (X, backdrop, Esc) sends the visitor back to the page
 * they came from.
 */
export default function RechargePrompt({ info }: Props) {
  const router = useRouter();

  const [mounted, setMounted] = useState(false);

  const amount = Math.ceil(info.shortfall);

  const handleClose = () => {
    if (window.history.length > 1) {
      router.back();
    } else {
      router.push("/");
    }
  };

  useEffect(() => {
    setMounted(true);

    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") handleClose();
    };

    window.addEventListener("keydown", onKeyDown);

    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener("keydown", onKeyDown);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!mounted) return null;

  return createPortal(
    <div className="recharge-modal-backdrop" onClick={handleClose}>
      <div
        className="recharge-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="recharge-modal-title"
        onClick={(event) => event.stopPropagation()}
      >
        <button
          type="button"
          className="recharge-modal-close"
          onClick={handleClose}
          aria-label="Close"
        >
          &times;
        </button>

        <h2 id="recharge-modal-title">
          Insufficient funds in your wallet. Please recharge your wallet to use
          this service.
        </h2>

        <p>{info.message}</p>

        <Link
          href={walletRechargeUrl(info.shortfall)}
          className="recharge-modal-btn"
        >
          {amount > 0 ? `Recharge wallet (add ₹${amount})` : "Recharge wallet"}
        </Link>
      </div>
    </div>,
    document.body
  );
}
