"use client";

import { useEffect, useState } from "react";
import {
  X,
  ShieldCheck,
  Loader2,
  AlertCircle,
  Package,
  CheckCircle,
  MapPin,
} from "lucide-react";
import { paymentService } from "@/services/paymentService";
import {
  orderService,
  isPaymentBypassEnabled,
  makeTestTransactionId,
  type MarketplaceOrder,
} from "@/services/orderService";
import { PayPalCheckout } from "@/components/payment/PayPalButtons";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";

interface PayOrderModalProps {
  order: MarketplaceOrder | null;
  onClose: () => void;
  /** Fired after the payment is captured and confirm_order_payment succeeds. */
  onPaid: (orderId: number) => void;
  onError: (message: string) => void;
}

export function PayOrderModal({
  order,
  onClose,
  onPaid,
  onError,
}: PayOrderModalProps) {
  const [clientId, setClientId] = useState("");
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState("");
  const [confirming, setConfirming] = useState(false);
  const [done, setDone] = useState(false);
  const [cancelNotice, setCancelNotice] = useState("");

  const { settings } = useGeneralSettings();
  const sym = settings?.currencySymbol ?? "$";
  const isOpen = !!order;

  useEffect(() => {
    if (!isOpen) return;
    setDone(false);
    setCancelNotice("");
    setLoading(true);
    setLoadError("");
    paymentService
      .getOptions()
      .then((opts) => {
        const paypal = opts.find((o) => o.name === "paypal");
        if (!paypal?.publicKey) {
          setLoadError("PayPal is not configured. Please try again later.");
        } else {
          setClientId(paypal.publicKey);
        }
      })
      .catch(() => setLoadError("Failed to load PayPal checkout."))
      .finally(() => setLoading(false));
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) return;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = "";
    };
  }, [isOpen]);

  if (!isOpen || !order) return null;

  const address = [order.address, order.city, order.state, order.country]
    .filter(Boolean)
    .join(", ");

  const handleSuccess = async (captureId: string) => {
    setConfirming(true);
    try {
      await orderService.confirmOrderPayment(order.id, 1, captureId);
    } catch {
      // Payment was captured — the backend will reconcile via transaction id.
    }
    setConfirming(false);
    setDone(true);
    window.setTimeout(() => onPaid(order.id), 1500);
  };

  const handleError = async (message: string) => {
    if (message === "Payment cancelled") {
      setCancelNotice("Payment was cancelled. You can try again below.");
      return;
    }
    try {
      await orderService.confirmOrderPayment(order.id, 2);
    } catch {
      // best effort — order stays payment-pending on the backend
    }
    onError(message);
  };

  const locked = confirming || done;

  return (
    <>
      <div
        className="fixed inset-0 z-[120]"
        style={{ background: "rgba(0,0,0,0.78)", backdropFilter: "blur(10px)" }}
        onClick={locked ? undefined : onClose}
      />
      <div
        className="fixed z-[121] flex flex-col overflow-hidden"
        style={{
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          width: "min(440px, 94vw)",
          maxHeight: "min(600px, 90vh)",
          background: "var(--card)",
          borderRadius: 20,
          border: "1px solid var(--border)",
          boxShadow: "0 32px 96px rgba(0,0,0,0.5)",
        }}
      >
        <div
          className="flex items-center justify-between px-5 pt-5 pb-4 shrink-0"
          style={{ borderBottom: "1px solid var(--border-soft)" }}
        >
          <div className="flex items-center gap-2">
            <ShieldCheck size={16} color="#10b981" strokeWidth={1.8} />
            <span
              className="text-sm font-bold"
              style={{ color: "var(--text-primary)" }}
            >
              {done ? "Payment Confirmed" : `Pay for Order #${order.id}`}
            </span>
          </div>
          {!done && (
            <button
              onClick={confirming ? undefined : onClose}
              className="w-7 h-7 rounded-full flex items-center justify-center transition-all hover:brightness-125"
              style={{ background: "var(--btn-ghost-hover)" }}
            >
              <X size={13} color="#888" />
            </button>
          )}
        </div>

        <div className="flex-1 overflow-y-auto scrollbar-thin px-5 py-4">
          {/* Item summary */}
          <div
            className="flex items-center gap-3 px-4 py-3 rounded-xl mb-4"
            style={{
              background: "var(--btn-ghost)",
              border: "1px solid var(--border-soft)",
            }}
          >
            {order.listingImage ? (
              <img
                src={order.listingImage}
                alt={order.listingName}
                className="w-12 h-12 rounded-lg object-cover shrink-0"
              />
            ) : (
              <div
                className="w-12 h-12 rounded-lg flex items-center justify-center shrink-0"
                style={{ background: "var(--bg)" }}
              >
                <Package size={18} color="var(--text-muted)" />
              </div>
            )}
            <div className="min-w-0 flex-1">
              <p
                className="text-[12px] font-semibold truncate"
                style={{ color: "var(--text-primary)" }}
              >
                {order.listingName || `Order #${order.id}`}
              </p>
              <p className="text-[10px]" style={{ color: "var(--text-muted)" }}>
                Qty: {order.quantity}
              </p>
            </div>
            <span
              className="text-base font-black shrink-0"
              style={{ color: "var(--text-primary)" }}
            >
              {sym}
              {order.price.toLocaleString()}
            </span>
          </div>

          {done ? (
            <div className="flex flex-col items-center gap-3 py-8">
              <div
                className="w-16 h-16 rounded-full flex items-center justify-center"
                style={{ background: "rgba(16,185,129,0.12)" }}
              >
                <CheckCircle size={32} color="#10b981" />
              </div>
              <p
                className="text-sm font-bold"
                style={{ color: "var(--text-primary)" }}
              >
                Payment Confirmed!
              </p>
              <p
                className="text-[11px] text-center"
                style={{ color: "var(--text-muted)" }}
              >
                Order #{order.id} payment completed successfully.
              </p>
              <Loader2
                size={16}
                color="var(--accent)"
                className="animate-spin"
              />
            </div>
          ) : (
            <>
              {/* Delivery summary */}
              {address && (
                <div
                  className="flex items-start gap-2 px-4 py-3 rounded-xl mb-4"
                  style={{
                    background: "var(--btn-ghost)",
                    border: "1px solid var(--border-soft)",
                  }}
                >
                  <MapPin
                    size={13}
                    color="var(--accent)"
                    className="mt-0.5 shrink-0"
                  />
                  <p
                    className="text-[11px] leading-relaxed"
                    style={{ color: "var(--text-muted)" }}
                  >
                    {address}
                    {order.pincode ? ` — ${order.pincode}` : ""}
                  </p>
                </div>
              )}

              {cancelNotice && (
                <div
                  className="flex items-center gap-2 py-2.5 px-4 rounded-xl text-[12px] mb-3"
                  style={{
                    background: "rgba(245,158,11,0.08)",
                    color: "#f59e0b",
                    border: "1px solid rgba(245,158,11,0.15)",
                  }}
                >
                  <AlertCircle size={14} strokeWidth={1.8} className="shrink-0" />
                  {cancelNotice}
                </div>
              )}

              {loading && (
                <div className="flex flex-col items-center gap-3 py-10">
                  <Loader2
                    size={28}
                    color="var(--accent)"
                    className="animate-spin"
                  />
                  <p className="text-xs" style={{ color: "#666" }}>
                    Connecting to PayPal…
                  </p>
                </div>
              )}

              {!loading && loadError && (
                <div
                  className="flex items-center gap-2 py-3 px-4 rounded-xl text-[12px]"
                  style={{
                    background: "rgba(244,63,94,0.08)",
                    color: "#f43f5e",
                    border: "1px solid rgba(244,63,94,0.15)",
                  }}
                >
                  <AlertCircle size={14} strokeWidth={1.8} className="shrink-0" />
                  {loadError}
                </div>
              )}

              {!loading && !loadError && confirming && (
                <div className="flex flex-col items-center gap-3 py-10">
                  <Loader2
                    size={28}
                    color="var(--accent)"
                    className="animate-spin"
                  />
                  <p className="text-xs" style={{ color: "#666" }}>
                    Confirming your payment…
                  </p>
                </div>
              )}

              {!loading && !loadError && !confirming && clientId && (
                <PayPalCheckout
                  clientId={clientId}
                  amount={order.price}
                  currency={settings?.currencyCode ?? "USD"}
                  itemName={order.listingName || `Order #${order.id}`}
                  quantity={order.quantity}
                  onSuccess={handleSuccess}
                  onError={handleError}
                />
              )}

              {!loading && !confirming && isPaymentBypassEnabled() && (
                <button
                  onClick={() =>
                    handleSuccess(makeTestTransactionId(order.id))
                  }
                  className="w-full flex items-center justify-center gap-2 rounded-xl py-2.5 mt-3 text-xs font-bold transition-all hover:brightness-110"
                  style={{
                    background: "rgba(245,158,11,0.08)",
                    color: "#f59e0b",
                    border: "1px dashed rgba(245,158,11,0.4)",
                  }}
                >
                  ⚡ Skip Payment (Test Mode)
                </button>
              )}
            </>
          )}

          <div className="flex items-center justify-center gap-1.5 mt-4">
            <ShieldCheck size={10} color="#555" />
            <span className="text-[9px]" style={{ color: "#444" }}>
              256-bit SSL encrypted · Secure checkout via PayPal
            </span>
          </div>
        </div>
      </div>
    </>
  );
}
