"use client";

/** What each gateway is called, rather than showing its key. */
const GATEWAY_NAMES: Record<string, string> = {
  razorpay: "Razorpay",
  paystack: "Paystack",
  flutterwave: "Flutterwave",
  mercadopago: "Mercado Pago",
  authorizeNet: "Authorize.net",
  coinbase: "Pay with crypto",
  coinpayments: "CoinPayments",
};


import { useModule } from "@/lib/modules";

import { useEffect, useState } from "react";
import { CreditCard, Loader2, AlertTriangle } from "lucide-react";
import clsx from "clsx";

type Options = {
  stripe: boolean;
  paypal: boolean;
  /** The other gateways an admin has switched on and configured. */
  extraGateways?: string[];
  bank?: {
    name: string;
    accountName: string;
    accountNumber: string;
    routing: string;
    country: string;
    note: string;
  } | null;
  symbol: string;
  min: number;
  max: number;
};

/**
 * Adding real money to the wallet. Only appears once an admin has set up a
 * gateway — otherwise there's nothing to offer.
 */
export function TopUpPanel() {
  // Hidden when this module is switched off in System settings.
  const moduleOn = useModule("wallet");

  const [options, setOptions] = useState<Options | null>(null);
  const [amount, setAmount] = useState("");
  const [busy, setBusy] = useState(false);
  const [problem, setProblem] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/payments/checkout")
      .then((r) => (r.ok ? r.json() : null))
      .then(setOptions)
      .catch(() => {});
  }, []);

  if (!moduleOn) return null;


  const extras = options?.extraGateways ?? [];
  // Nothing to show only when every route is off.
  if (!options || (!options.stripe && !options.paypal && extras.length === 0 && !options.bank)) {
    return null;
  }

  async function start(provider: string) {
    setBusy(true);
    setProblem(null);

    const res = await fetch("/api/payments/checkout", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ amount: Number(amount), provider }),
    }).catch(() => null);

    const d = res ? await res.json() : null;
    setBusy(false);

    if (!res || !res.ok) {
      setProblem(d?.error ?? "Couldn't start that payment");
      return;
    }

    // Both providers need their own hosted step; this hands off to it.
    if (provider === "paypal" && d.orderId) {
      window.location.href = `https://www.paypal.com/checkoutnow?token=${d.orderId}`;
      return;
    }
    if (provider === "stripe" && d.clientSecret) {
      sessionStorage.setItem("xr_payment", d.clientSecret);
      window.location.href = `/wallet/pay?secret=${encodeURIComponent(d.clientSecret)}`;
    }
  }

  const preset = [10, 25, 50, 100];

  return (
    <div className="tu-card">
      <h3>
        <CreditCard size={17} /> Add money
      </h3>
      <p className="tu-hint">
        Between {options.symbol}
        {options.min} and {options.symbol}
        {options.max}.
      </p>

      <div className="tu-presets">
        {preset.map((v) => (
          <button
            key={v}
            onClick={() => setAmount(String(v))}
            className={clsx("tu-preset", amount === String(v) && "on")}
          >
            {options.symbol}
            {v}
          </button>
        ))}
      </div>

      <input
        type="number"
        value={amount}
        onChange={(e) => setAmount(e.target.value)}
        placeholder="Or type an amount"
        className="wd-input"
      />

      <div className="tu-buttons">
        {options.stripe && (
          <button onClick={() => start("stripe")} disabled={busy || !amount} className="tu-pay">
            {busy ? <Loader2 size={15} className="animate-spin" /> : <CreditCard size={15} />}
            Pay by card
          </button>
        )}
        {options.paypal && (
          <button onClick={() => start("paypal")} disabled={busy || !amount} className="tu-paypal">
            PayPal
          </button>
        )}

      {/* The other gateways were built and configured but never offered,
          so nobody could pay with them. */}
      {extras.map((name) => (
        <button key={name} onClick={() => start(name)} className="tp-option">
          {GATEWAY_NAMES[name] ?? name}
        </button>
      ))}

      {options.bank && (
        <details className="tp-bank">
          <summary>Pay by bank transfer</summary>
          <dl>
            <dt>Bank</dt><dd>{options.bank.name}</dd>
            <dt>Account name</dt><dd>{options.bank.accountName}</dd>
            <dt>Account</dt><dd>{options.bank.accountNumber}</dd>
            <dt>Sort code / SWIFT</dt><dd>{options.bank.routing}</dd>
          </dl>
          {options.bank.note && <p>{options.bank.note}</p>}
        </details>
      )}
      </div>

      {problem && (
        <p className="em-problem">
          <AlertTriangle size={13} /> {problem}
        </p>
      )}
    </div>
  );
}
