"use client";

import { useState, useEffect, useRef } from "react";
import { useTranslations, useLocale } from "next-intl";
import { useRouter } from "next/navigation";
import { Wallet, CreditCard, Loader2 } from "lucide-react";
import { useWalletBalances } from "@/lib/clientQueries";
import { payWithWallet, payWithGateway } from "@/actions/payment";
import {
  buildReturnPathForGatewayRequest,
  persistGatewayMetaFromGatewayResponse,
} from "@/lib/payment-return";
import { useAppToast } from "@/app/[lang]/providers";
import { useApplePayVisible } from "@/lib/platform";
import { toMoneyNumber } from "@/lib/moneyParse";
import PaymentGatewayModal from "./PaymentGatewayModal";

export type PaymentMethod = "wallet" | "gateway" | "apple_pay";

export interface PaymentParams {
  payment_purpose: string;
  offer_id?: string;
  auction_id?: string;
  single_auction_id?: string;
  auction_type?: "normal" | "annual" | string;
  payment_type?: "full" | "deposit" | string;
  market_transaction_id?: string;
  paddle_subscription_id?: string;
}

interface PaymentMethodSelectorProps {
  amount: number;
  paymentParams: PaymentParams;
  onSuccess?: () => void;
  onError?: (error: string) => void;
  disabled?: boolean;
  showSummary?: boolean;
  className?: string;
}

export default function PaymentMethodSelector({
  amount,
  paymentParams,
  onSuccess,
  onError,
  disabled = false,
  showSummary = true,
  className = "",
}: PaymentMethodSelectorProps) {
  const t = useTranslations("PAYMENT");
  const tToast = useTranslations("TOAST");
  const locale = useLocale();
  const router = useRouter();
  const toast = useAppToast();
  const isAr = locale === "ar";

  const { data: balances, isLoading: balancesLoading } = useWalletBalances();
  const walletBalance = toMoneyNumber(balances?.available_balance, 0);
  const payableAmount = toMoneyNumber(amount, 0);
  const canAffordWithWallet = walletBalance >= payableAmount;
  const applePayVisible = useApplePayVisible();

  const [method, setMethod] = useState<PaymentMethod>("gateway");
  const [isProcessing, setIsProcessing] = useState(false);
  const [showInsufficientModal, setShowInsufficientModal] = useState(false);
  const [showGatewayModal, setShowGatewayModal] = useState(false);
  const [gatewayUrl, setGatewayUrl] = useState<string | null>(null);
  const gatewayOpeningRef = useRef(false);

  useEffect(() => {
    if (!balancesLoading && method === "wallet" && !canAffordWithWallet) {
      setShowInsufficientModal(true);
    }
  }, [balancesLoading, method, canAffordWithWallet]);

  const handlePayment = async () => {
    if (isProcessing || disabled) return;

    if (method === "wallet") {
      if (!canAffordWithWallet) {
        setShowInsufficientModal(true);
        return;
      }

      try {
        setIsProcessing(true);
        const res = await payWithWallet(paymentParams);

        if ((res as any)?.success) {
          toast.success(tToast("payment_success_short"));
          onSuccess?.();
        } else {
          const msg =
            (res as any)?.message ||
            (res as any)?.error ||
            tToast("payment_failed");
          toast.error(msg);
          onError?.(msg);
        }
      } catch (e: any) {
        const msg =
          e?.info?.message ||
          e?.message ||
          tToast("payment_error");
        toast.error(msg);
        onError?.(msg);
      } finally {
        setIsProcessing(false);
      }
    } else {
      // Both "gateway" (online_payment) and "apple_pay" go through payWithGateway
      const selectedPaymentMethod =
        method === "apple_pay" ? "apple_pay" : "online_payment";

      try {
        if (gatewayOpeningRef.current) return;
        gatewayOpeningRef.current = true;
        setIsProcessing(true);
        const returnPath = buildReturnPathForGatewayRequest() ?? "/";
        const res = await payWithGateway({
          ...paymentParams,
          payment_method: selectedPaymentMethod,
          return_path: returnPath,
        });

        const resolvedGatewayUrl =
          (res as any)?.data?.payment_url || (res as any)?.data?.redirect_url;

        if ((res as any)?.success && resolvedGatewayUrl) {
          if (typeof window !== "undefined") {
            persistGatewayMetaFromGatewayResponse(
              (res as any)?.data as Record<string, unknown>,
              returnPath,
            );
            window.open(resolvedGatewayUrl, "_blank");
          }
        } else {
          const msg =
            (res as any)?.message ||
            (res as any)?.error ||
            tToast("gateway_payment_failed");
          toast.error(msg);
          onError?.(msg);
        }
      } catch (e: any) {
        const msg =
          e?.info?.message ||
          e?.message ||
          tToast("payment_error");
        toast.error(msg);
        onError?.(msg);
      } finally {
        setIsProcessing(false);
        gatewayOpeningRef.current = false;
      }
    }
  };

  const handleTopUpWallet = () => {
    setShowInsufficientModal(false);
    router.push(`/${locale}/dashboard?tab=wallet-request`);
  };

  const handleSwitchToGateway = () => {
    setShowInsufficientModal(false);
    setMethod("gateway");
  };

  if (balancesLoading) {
    return (
      <div className={`space-y-3 ${className}`}>
        {[1, 2].map((i) => (
          <div key={i} className="border rounded-xl p-4 bg-white animate-pulse">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="w-5 h-5 rounded-full bg-slate-200" />
                <div>
                  <div className="h-4 w-32 bg-slate-200 rounded" />
                  <div className="h-3 w-48 bg-slate-100 rounded mt-2" />
                </div>
              </div>
              <div className="h-6 w-20 bg-slate-100 rounded" />
            </div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className={`space-y-4 ${className}`}>
      <div className="space-y-3">
        <label
          className={`border rounded-xl p-4 flex items-center justify-between bg-white transition cursor-pointer hover:border-[#145c3a] hover:shadow-md ${
            method === "gateway"
              ? "border-[#0f5132] ring-2 ring-[#0f5132]/20"
              : ""
          }`}
        >
          <div className="flex items-center gap-3">
            <input
              type="radio"
              name="paymentMethod"
              checked={method === "gateway"}
              onChange={() => setMethod("gateway")}
              className="accent-[#0f5132] w-5 h-5"
              disabled={disabled}
            />
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-blue-50 flex items-center justify-center">
                <CreditCard className="w-5 h-5 text-blue-600" />
              </div>
              <div>
                <div className="font-semibold text-sm">
                  {t("gateway_title")}
                </div>
                <div className="text-slate-500 text-xs">
                  {t("gateway_desc")}
                </div>
              </div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-8 h-5 rounded bg-[#1a1f71] grid place-items-center">
              <span className="text-[8px] text-white font-bold">VISA</span>
            </div>
            <div className="w-8 h-5 rounded bg-white border grid place-items-center">
              <div className="flex">
                <div className="w-2 h-2 rounded-full bg-[#eb001b]" />
                <div className="w-2 h-2 rounded-full bg-[#f79e1b] -ml-1" />
              </div>
            </div>
            <div className="w-8 h-5 rounded bg-[#f0fdf9] border grid place-items-center">
              <span className="text-[6px] text-emerald-600 font-bold">
                mada
              </span>
            </div>
          </div>
        </label>

        {applePayVisible && (
          <label
            className={`border rounded-xl p-4 flex items-center justify-between bg-white transition cursor-pointer hover:border-[#145c3a] hover:shadow-md ${
              method === "apple_pay"
                ? "border-[#0f5132] ring-2 ring-[#0f5132]/20"
                : ""
            }`}
          >
            <div className="flex items-center gap-3">
              <input
                type="radio"
                name="paymentMethod"
                checked={method === "apple_pay"}
                onChange={() => setMethod("apple_pay")}
                className="accent-[#0f5132] w-5 h-5"
                disabled={disabled}
              />
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-slate-900 flex items-center justify-center">
                  <svg viewBox="0 0 24 24" className="w-5 h-5 fill-white" aria-hidden="true">
                    <path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.7 9.05 7.4c1.28.07 2.16.72 2.98.73 1.16-.1 2.26-.79 3.47-.68 1.45.13 2.54.79 3.25 2.02-3.13 1.87-2.39 5.88.3 6.97-.5 1.32-1.29 2.59-2 3.84zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/>
                  </svg>
                </div>
                <div>
                  <div className="font-semibold text-sm">
                    {t("apple_pay_title")}
                  </div>
                  <div className="text-slate-500 text-xs">
                    {t("apple_pay_desc")}
                  </div>
                </div>
              </div>
            </div>
            <div className="flex items-center gap-1">
              <div className="h-6 px-2 rounded bg-black flex items-center gap-1">
                <svg viewBox="0 0 24 24" className="w-3 h-3 fill-white" aria-hidden="true">
                  <path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.7 9.05 7.4c1.28.07 2.16.72 2.98.73 1.16-.1 2.26-.79 3.47-.68 1.45.13 2.54.79 3.25 2.02-3.13 1.87-2.39 5.88.3 6.97-.5 1.32-1.29 2.59-2 3.84zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/>
                </svg>
                <span className="text-white text-[9px] font-semibold tracking-tight">Pay</span>
              </div>
            </div>
          </label>
        )}

        <label
          className={`border rounded-xl p-4 flex items-center justify-between bg-white transition cursor-pointer hover:border-[#145c3a] hover:shadow-md ${
            method === "wallet"
              ? "border-[#0f5132] ring-2 ring-[#0f5132]/20"
              : ""
          }`}
        >
          <div className="flex items-center gap-3">
            <input
              type="radio"
              name="paymentMethod"
              checked={method === "wallet"}
              onChange={() => setMethod("wallet")}
              className="accent-[#0f5132] w-5 h-5"
              disabled={disabled}
            />
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-emerald-50 flex items-center justify-center">
                <Wallet className="w-5 h-5 text-emerald-600" />
              </div>
              <div>
                <div className="font-semibold text-sm">{t("wallet_title")}</div>
                <div className="text-slate-500 text-xs">
                  {t("wallet_balance")}: <b>{walletBalance.toLocaleString()}</b>{" "}
                  {t("currency")}
                  {!canAffordWithWallet && (
                    <span className="text-red-500 mr-2">
                      ({t("insufficient")})
                    </span>
                  )}
                </div>
              </div>
            </div>
          </div>
          <div className="w-10 h-6 rounded-md bg-[#145c3a] grid place-items-center">
            <Wallet className="w-4 h-4 text-white" />
          </div>
        </label>
      </div>

      {showSummary && (
        <div className="bg-white border border-slate-200 rounded-xl p-4 text-sm">
          <div className="flex items-center justify-between py-1">
            <span className="text-slate-600">{t("payment_method_label")}</span>
            <span className="font-medium">
              {method === "wallet"
                ? t("wallet_title")
                : method === "apple_pay"
                  ? t("apple_pay_title")
                  : t("gateway_title")}
            </span>
          </div>
          <div className="flex items-center justify-between pt-2 mt-2 border-t border-dashed font-bold">
            <span>{t("total")}</span>
            <span className="text-[#0f5132]">
              {payableAmount.toLocaleString()} {t("currency")}
            </span>
          </div>
        </div>
      )}

      <button
        type="button"
        onClick={handlePayment}
        disabled={isProcessing || disabled}
        className="w-full bg-[#0f5132] hover:bg-[#0d4429] disabled:bg-slate-300 text-white font-bold py-3 px-6 rounded-xl transition flex items-center justify-center gap-2"
      >
        {isProcessing ? (
          <>
            <Loader2 className="w-5 h-5 animate-spin" />
            {t("processing")}
          </>
        ) : (
          <>
            {method === "wallet" ? (
              <Wallet className="w-5 h-5" />
            ) : method === "apple_pay" ? (
              <svg viewBox="0 0 24 24" className="w-5 h-5 fill-white" aria-hidden="true">
                <path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.7 9.05 7.4c1.28.07 2.16.72 2.98.73 1.16-.1 2.26-.79 3.47-.68 1.45.13 2.54.79 3.25 2.02-3.13 1.87-2.39 5.88.3 6.97-.5 1.32-1.29 2.59-2 3.84zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/>
              </svg>
            ) : (
              <CreditCard className="w-5 h-5" />
            )}
            {t("pay_now")}
          </>
        )}
      </button>

      {showInsufficientModal && (
        <div
          className="fixed inset-0 flex items-center justify-center bg-black/50 p-4 z-50"
          role="dialog"
          aria-modal="true"
        >
          <div className="w-full max-w-md bg-white rounded-2xl shadow-xl overflow-hidden">
            <div className="bg-[#0f5132] text-white px-5 py-4 font-bold">
              {t("insufficient_title")}
            </div>
            <div className="p-5 space-y-3">
              <p className="text-slate-600">{t("insufficient_desc")}</p>
              <div className="bg-slate-50 rounded-xl p-3 text-sm">
                <div className="flex justify-between">
                  <span>{t("wallet_balance")}:</span>
                  <span className="font-bold">
                    {walletBalance.toLocaleString()} {t("currency")}
                  </span>
                </div>
                <div className="flex justify-between mt-1">
                  <span>{t("required")}:</span>
                  <span className="font-bold text-red-600">
                    {payableAmount.toLocaleString()} {t("currency")}
                  </span>
                </div>
              </div>
            </div>
            <div className="flex gap-3 px-5 pb-5">
              <button
                className="flex-1 bg-white text-[#0f5132] border border-[#0f5132] px-4 py-2.5 rounded-xl font-medium hover:bg-emerald-50 transition"
                onClick={() => setShowInsufficientModal(false)}
              >
                {t("cancel")}
              </button>
              <button
                className="flex-1 bg-amber-500 hover:bg-amber-600 text-white px-4 py-2.5 rounded-xl font-medium transition"
                onClick={handleTopUpWallet}
              >
                {t("top_up_wallet")}
              </button>
              <button
                className="flex-1 bg-[#0f5132] hover:bg-[#0d4429] text-white px-4 py-2.5 rounded-xl font-medium transition"
                onClick={handleSwitchToGateway}
              >
                {t("use_gateway")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Payment Gateway Modal */}
      {gatewayUrl && (
        <PaymentGatewayModal
          isOpen={showGatewayModal}
          onClose={() => {
            setShowGatewayModal(false);
            setGatewayUrl(null);
          }}
          gatewayUrl={gatewayUrl}
          isAr={isAr}
        />
      )}
    </div>
  );
}
