"use client";

import { useEffect, useState } from "react";
import {
  X,
  ShieldCheck,
  Loader2,
  AlertCircle,
  MapPin,
  Minus,
  Plus,
  ArrowLeft,
  PackageCheck,
} from "lucide-react";
import { paymentService } from "@/services/paymentService";
import { profileService } from "@/services/profileService";
import {
  orderService,
  isPaymentBypassEnabled,
  makeTestTransactionId,
  type MarketplaceOrder,
} from "@/services/orderService";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";
import { useAppSelector } from "@/store/hooks";

export interface BuyNowListing {
  id: string;
  title: string;
  price: number;
  image?: string;
  /** The URL slug for this listing — used to build the PayPal cancel URL. */
  listingSlug?: string;
  /** Stock from get_listing_detail — caps the quantity selector. */
  availableQuantity?: number;
}

interface BuyNowModalProps {
  listing: BuyNowListing | null;
  onClose: () => void;
  onSuccess: (orderId: number) => void;
  onError: (message: string) => void;
}

interface AddressForm {
  address: string;
  city: string;
  state: string;
  country: string;
  pincode: string;
}

const MAX_QTY = 10;
const BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH ?? "";

export function BuyNowModal({
  listing,
  onClose,
  onSuccess,
  onError,
}: BuyNowModalProps) {
  const [hasPayPal, setHasPayPal] = useState(false);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState("");
  const [step, setStep] = useState<"form" | "payment">("form");
  const [quantity, setQuantity] = useState(1);
  const [form, setForm] = useState<AddressForm>({
    address: "",
    city: "",
    state: "",
    country: "",
    pincode: "",
  });
  const [formError, setFormError] = useState("");
  const [placing, setPlacing] = useState(false);
  const [redirecting, setRedirecting] = useState(false);
  const [order, setOrder] = useState<MarketplaceOrder | null>(null);
  const [savedAddress, setSavedAddress] = useState<AddressForm | null>(null);

  const { settings } = useGeneralSettings();
  const authUser = useAppSelector((s) => s.auth.user);
  const sym = settings?.currencySymbol ?? "$";
  const currencyCode = settings?.currencyCode ?? "USD";
  const isOpen = !!listing;
  const total = (listing?.price ?? 0) * quantity;
  const maxQty = Math.min(
    MAX_QTY,
    Math.max(1, listing?.availableQuantity ?? MAX_QTY),
  );

  /* Reset + prefill whenever the modal opens */
  useEffect(() => {
    if (!isOpen) return;
    setStep("form");
    setQuantity(1);
    setOrder(null);
    setFormError("");
    setRedirecting(false);
    setForm((f) => ({
      ...f,
      city: authUser?.city ?? f.city,
      state: authUser?.state ?? f.state,
    }));
    setSavedAddress(null);
    profileService
      .getProfile()
      .then((res) => {
        const p = res.result?.[0];
        if (
          p?.address?.trim() &&
          p?.city?.trim() &&
          p?.state?.trim() &&
          p?.country?.trim() &&
          Number(p?.pincode) > 0
        ) {
          setSavedAddress({
            address: p.address.trim(),
            city: p.city.trim(),
            state: p.state.trim(),
            country: p.country.trim(),
            pincode: String(p.pincode),
          });
        }
      })
      .catch(() => {});
    setLoading(true);
    setLoadError("");
    paymentService
      .getOptions()
      .then((opts) => {
        const paypal = opts.find((o) => o.name === "paypal");
        if (!paypal?.publicKey) {
          setLoadError("PayPal is not configured. Please contact support.");
        } else {
          setHasPayPal(true);
        }
      })
      .catch(() => setLoadError("Failed to load payment options."))
      .finally(() => setLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen]);

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

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

  const setField = (key: keyof AddressForm, value: string) => {
    setForm((f) => ({ ...f, [key]: value }));
    setFormError("");
  };

  /* ── Step 1: validate form + create backend order ── */
  const handleContinue = async () => {
    const missing = (
      ["address", "city", "state", "country", "pincode"] as const
    ).filter((k) => !form[k].trim());
    if (missing.length > 0) {
      setFormError("Please fill in all delivery address fields.");
      return;
    }
    if (!/^\d{4,10}$/.test(form.pincode.trim())) {
      setFormError("Please enter a valid pincode.");
      return;
    }
    if (quantity > maxQty) {
      setFormError(`Only ${maxQty} unit${maxQty > 1 ? "s" : ""} available.`);
      return;
    }
    setPlacing(true);
    setFormError("");
    try {
      const created = await orderService.initiateOrder({
        listingId: listing.id,
        quantity,
        address: form.address.trim(),
        city: form.city.trim(),
        state: form.state.trim(),
        country: form.country.trim(),
        pincode: form.pincode.trim(),
      });
      setOrder(created);
      setStep("payment");
    } catch (err) {
      setFormError(
        err instanceof Error && err.message
          ? err.message
          : "Could not place the order. Please try again.",
      );
    } finally {
      setPlacing(false);
    }
  };

  /* ── Step 2: redirect to PayPal checkout ── */
  const handlePayPalRedirect = async () => {
    if (!order) return;
    setRedirecting(true);
    setFormError("");
    try {
      const origin = typeof window !== "undefined" ? window.location.origin : "";
      const returnUrl =
        `${origin}${BASE_PATH}/marketplace/payment/success` +
        `?orderId=${order.id}`;
      const slug = listing.listingSlug ?? "";
      const cancelUrl =
        `${origin}${BASE_PATH}/marketplace/payment/failed` +
        `?orderId=${order.id}&listingSlug=${encodeURIComponent(slug)}&cancelled=1`;

      const res = await fetch(`${BASE_PATH}/api/paypal/create-redirect-order`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          amount: total,
          currency: currencyCode,
          itemName: listing.title,
          quantity,
          returnUrl,
          cancelUrl,
        }),
      });
      const data = await res.json();
      if (!res.ok || !data.approvalUrl) {
        throw new Error(data.error ?? "Failed to create PayPal checkout.");
      }
      // Full-page redirect to PayPal — buyer returns to returnUrl on success
      window.location.href = data.approvalUrl as string;
    } catch (err) {
      setRedirecting(false);
      setFormError(
        err instanceof Error ? err.message : "Could not connect to PayPal.",
      );
    }
  };

  /* ── Dev-only bypass ── */
  const handleTestBypass = async () => {
    if (!order) return;
    setRedirecting(true);
    try {
      await orderService.confirmOrderPayment(
        order.id,
        1,
        makeTestTransactionId(order.id),
      );
      onSuccess(order.id);
    } catch {
      onError("Test bypass failed.");
    } finally {
      setRedirecting(false);
    }
  };

  const inputStyle: React.CSSProperties = {
    background: "var(--btn-ghost)",
    border: "1px solid var(--border-soft)",
    color: "var(--text-primary)",
  };

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 z-[120]"
        style={{ background: "rgba(0,0,0,0.78)", backdropFilter: "blur(10px)" }}
        onClick={redirecting ? undefined : onClose}
      />

      {/* Modal */}
      <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(640px, 90vh)",
          background: "var(--card)",
          borderRadius: 20,
          border: "1px solid var(--border)",
          boxShadow: "0 32px 96px rgba(0,0,0,0.5)",
        }}
      >
        {/* Header */}
        <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">
            {step === "payment" && !redirecting && (
              <button
                onClick={() => setStep("form")}
                className="w-6 h-6 rounded-full flex items-center justify-center transition-all hover:brightness-125"
                style={{ background: "var(--btn-ghost-hover)" }}
              >
                <ArrowLeft size={12} color="#888" />
              </button>
            )}
            <ShieldCheck size={16} color="#10b981" strokeWidth={1.8} />
            <span
              className="text-sm font-bold"
              style={{ color: "var(--text-primary)" }}
            >
              {step === "form" ? "Buy It Now" : "Confirm & Pay"}
            </span>
          </div>
          {!redirecting && (
            <button
              onClick={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>

        {/* Body */}
        <div className="flex-1 overflow-y-auto scrollbar-thin px-5 py-4">

          {/* Item summary (both steps) */}
          <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)",
            }}
          >
            {listing.image && (
              <img
                src={listing.image}
                alt={listing.title}
                className="w-12 h-12 rounded-lg object-cover shrink-0"
              />
            )}
            <div className="min-w-0 flex-1">
              <p
                className="text-[12px] font-semibold truncate"
                style={{ color: "var(--text-primary)" }}
              >
                {listing.title}
              </p>
              <p className="text-[10px]" style={{ color: "var(--text-muted)" }}>
                Qty: {quantity} · {sym}
                {listing.price.toLocaleString()} each
              </p>
            </div>
            <span
              className="text-base font-black shrink-0"
              style={{ color: "var(--text-primary)" }}
            >
              {sym}
              {total.toLocaleString()}
            </span>
          </div>

          {/* ─── Step: form ─────────────────────────────────── */}
          {step === "form" && (
            <>
              {/* Quantity */}
              <div className="flex items-center justify-between mb-4">
                <div>
                  <span
                    className="text-xs font-semibold"
                    style={{ color: "var(--text-primary)" }}
                  >
                    Quantity
                  </span>
                  {listing.availableQuantity !== undefined && (
                    <p
                      className="text-[10px] mt-0.5"
                      style={{
                        color:
                          listing.availableQuantity <= 3
                            ? "#f59e0b"
                            : "var(--text-muted)",
                      }}
                    >
                      {listing.availableQuantity} available
                    </p>
                  )}
                </div>
                <div
                  className="flex items-center gap-3 rounded-xl px-2 py-1.5"
                  style={{
                    background: "var(--btn-ghost)",
                    border: "1px solid var(--border-soft)",
                  }}
                >
                  <button
                    onClick={() => setQuantity((q) => Math.max(1, q - 1))}
                    disabled={quantity <= 1}
                    className="w-6 h-6 rounded-lg flex items-center justify-center disabled:opacity-30"
                    style={{ background: "var(--btn-ghost-hover)" }}
                  >
                    <Minus size={11} color="#888" />
                  </button>
                  <span
                    className="text-sm font-bold w-6 text-center"
                    style={{ color: "var(--text-primary)" }}
                  >
                    {quantity}
                  </span>
                  <button
                    onClick={() => setQuantity((q) => Math.min(maxQty, q + 1))}
                    disabled={quantity >= maxQty}
                    className="w-6 h-6 rounded-lg flex items-center justify-center disabled:opacity-30"
                    style={{ background: "var(--btn-ghost-hover)" }}
                  >
                    <Plus size={11} color="#888" />
                  </button>
                </div>
              </div>

              {/* Delivery address */}
              <div className="flex items-center gap-1.5 mb-2">
                <MapPin size={12} color="var(--accent)" />
                <span
                  className="text-xs font-semibold"
                  style={{ color: "var(--text-primary)" }}
                >
                  Delivery Address
                </span>
                {savedAddress && (
                  <button
                    onClick={() => {
                      setForm(savedAddress);
                      setFormError("");
                    }}
                    className="ml-auto text-[10px] font-bold px-2.5 py-1 rounded-full transition-all hover:brightness-110"
                    style={{
                      background: "rgba(16,185,129,0.1)",
                      color: "#10b981",
                      border: "1px solid rgba(16,185,129,0.25)",
                    }}
                  >
                    Use saved address
                  </button>
                )}
              </div>
              <div className="space-y-2.5 mb-4">
                <input
                  value={form.address}
                  onChange={(e) => setField("address", e.target.value)}
                  placeholder="Street address / area"
                  className="w-full rounded-xl px-3.5 py-2.5 text-[13px] outline-none"
                  style={inputStyle}
                />
                <div className="grid grid-cols-2 gap-2.5">
                  <input
                    value={form.city}
                    onChange={(e) => setField("city", e.target.value)}
                    placeholder="City"
                    className="rounded-xl px-3.5 py-2.5 text-[13px] outline-none"
                    style={inputStyle}
                  />
                  <input
                    value={form.state}
                    onChange={(e) => setField("state", e.target.value)}
                    placeholder="State"
                    className="rounded-xl px-3.5 py-2.5 text-[13px] outline-none"
                    style={inputStyle}
                  />
                </div>
                <div className="grid grid-cols-2 gap-2.5">
                  <input
                    value={form.country}
                    onChange={(e) => setField("country", e.target.value)}
                    placeholder="Country"
                    className="rounded-xl px-3.5 py-2.5 text-[13px] outline-none"
                    style={inputStyle}
                  />
                  <input
                    value={form.pincode}
                    onChange={(e) =>
                      setField("pincode", e.target.value.replace(/\D/g, ""))
                    }
                    placeholder="Pincode"
                    inputMode="numeric"
                    maxLength={10}
                    className="rounded-xl px-3.5 py-2.5 text-[13px] outline-none"
                    style={inputStyle}
                  />
                </div>
              </div>

              {formError && (
                <div
                  className="flex items-center gap-2 py-2.5 px-4 rounded-xl text-[12px] mb-3"
                  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" />
                  {formError}
                </div>
              )}

              <button
                onClick={handleContinue}
                disabled={placing || loading || (!!loadError && !isPaymentBypassEnabled())}
                className="w-full flex items-center justify-center gap-2 rounded-xl py-3 text-sm font-bold text-white transition-all hover:brightness-110 disabled:opacity-50"
                style={{ background: "var(--accent)" }}
              >
                {placing ? (
                  <>
                    <Loader2 size={15} className="animate-spin" />
                    Creating order…
                  </>
                ) : (
                  <>
                    Continue · {sym}
                    {total.toLocaleString()}
                  </>
                )}
              </button>

              {!loading && loadError && (
                <div
                  className="flex items-center gap-2 py-2.5 px-4 rounded-xl text-[12px] mt-3"
                  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>
              )}
            </>
          )}

          {/* ─── Step: payment (confirm + redirect) ──────── */}
          {step === "payment" && (
            <>
              {order && (
                <div
                  className="flex items-center gap-2.5 px-4 py-3 rounded-xl mb-4"
                  style={{
                    background: "rgba(16,185,129,0.08)",
                    border: "1px solid rgba(16,185,129,0.2)",
                  }}
                >
                  <PackageCheck size={16} color="#10b981" className="shrink-0" />
                  <div className="min-w-0">
                    <p
                      className="text-[12px] font-bold"
                      style={{ color: "#10b981" }}
                    >
                      Order #{order.id} created
                    </p>
                    <p className="text-[10px]" style={{ color: "var(--text-muted)" }}>
                      Click below to complete payment on PayPal.
                    </p>
                  </div>
                </div>
              )}

              {/* Delivery summary */}
              <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)" }}>
                  {form.address}, {form.city}, {form.state}, {form.country} — {form.pincode}
                </p>
              </div>

              {formError && (
                <div
                  className="flex items-center gap-2 py-2.5 px-4 rounded-xl text-[12px] mb-3"
                  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" />
                  {formError}
                </div>
              )}

              {/* PayPal redirect button */}
              <button
                onClick={handlePayPalRedirect}
                disabled={redirecting || !hasPayPal}
                className="w-full flex items-center justify-center gap-3 rounded-xl py-3.5 font-bold text-white transition-all hover:brightness-110 disabled:opacity-60"
                style={{ background: "#0070ba" }}
              >
                {redirecting ? (
                  <>
                    <Loader2 size={16} className="animate-spin" />
                    Redirecting to PayPal…
                  </>
                ) : (
                  <>
                    {/* PayPal logo mark */}
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M20.07 6.35C20.34 4.55 20.07 3.32 19.08 2.18C18 0.95 16.1 0.4 13.67 0.4H6.27C5.72 0.4 5.25 0.8 5.17 1.35L2.18 20.27C2.12 20.68 2.43 21.05 2.85 21.05H7.32L8.45 14.01L8.41 14.26C8.49 13.71 8.95 13.31 9.5 13.31H11.68C16.04 13.31 19.44 11.5 20.47 6.39C20.5 6.37 20.07 6.35 20.07 6.35Z" fill="white" fillOpacity="0.9"/>
                      <path d="M9.21 6.72C9.28 6.35 9.52 6.06 9.83 5.93C9.97 5.87 10.13 5.84 10.3 5.84H15.84C16.5 5.84 17.11 5.88 17.66 5.97C17.83 5.99 17.99 6.03 18.15 6.07C18.3 6.11 18.45 6.16 18.59 6.22C18.66 6.25 18.73 6.27 18.79 6.3C19.05 6.42 19.29 6.56 19.49 6.73C19.76 4.93 19.48 3.7 18.5 2.56C17.41 1.32 15.51 0.77 13.08 0.77H5.68C5.13 0.77 4.66 1.17 4.58 1.72L1.59 20.64C1.53 21.04 1.84 21.42 2.25 21.42H7.01L8.18 14.08L9.21 6.72Z" fill="white"/>
                    </svg>
                    Pay {sym}{total.toLocaleString()} with PayPal
                  </>
                )}
              </button>

              <p className="text-[10px] text-center mt-2" style={{ color: "var(--text-muted)" }}>
                You will be redirected to PayPal to complete your payment securely.
              </p>

              {/* Dev-only test bypass */}
              {isPaymentBypassEnabled() && order && !redirecting && (
                <button
                  onClick={handleTestBypass}
                  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>
    </>
  );
}
